2010-10-01 41 views
0

我正在运行C#程序(即将转换为Windows服务的控制台应用程序),我需要能够通过电子邮件向管理员了解服务中的错误,但我需要它不发送我们的电子邮件对于每个错误,如果最近几分钟内的错误数量超过了4-5,那么它只会发送一封电子邮件,说有多个错误。时间已过或整数达到指定限制 - 如何? (C#)

我知道我会用某种形式的计时器,但任何人都可以提供更具体的建议吗?我会非常感谢

回答

0

从MSDN修改。请注意有关Timer对象aTimer的声明和清理的注释。

using System; 
using System.Timers; 
using System.Threading; 

public class Timer2 
{ 
    private static System.Timers.Timer aTimer; 
    private static List<string> errors = new List<string>(); 
    private static readonly int interval = 300000; // 5 minutes at present 
    private static readonly int trigger = 10;  // send msg if > 10 errors 

    // Message processing - error detection 
    public static void processMessage(Message message) 
    { 
     // do the work here 
     // then check error 
     if (message.HasError) 
     { 
     // add error to pending list 
     lock (errors) 
     { 
      string newErrorData = "got another one!"; 
      errors.Add(newErrorData); 
      ++trigger; 
     } 
     } 
    } 

    public static void Main() 
    { 
     // Normally, the timer is declared at the class level, 
     // so that it stays in scope as long as it is needed. 
     // If the timer is declared in a long-running method, 
     // KeepAlive must be used to prevent the JIT compiler 
     // from allowing aggressive garbage collection to occur 
     // before the method ends. (See end of method.) 
     //System.Timers.Timer aTimer; 

     // Create a timer with specified interval. 
     aTimer = new System.Timers.Timer(interval); 

     // Hook up the event handler for the Elapsed event. 
     aTimer.Elapsed += new ElapsedEventHandler(OnTimedEvent); 
     aTimer.Enabled = true; 

     // Kick off message handling - don't forget to clean up the timer when 
     // you wish to exit 
     while (moreMessages) 
     { 
      Message message = getNextmessage(); 
      ProcessMessage(message); 
     } 
     // cleanup here when messages are drained 
     // If the timer is declared in a long-running method, use 
     // KeepAlive to prevent garbage collection from occurring 
     // before the method ends. 
     //GC.KeepAlive(aTimer);  } 

    private static void OnTimedEvent(object source, ElapsedEventArgs e) 
    { 
     object errorEmail = null; 
     lock (errors) 
     { 
      if (errors.Count > trigger) 
      { 
       // init message to contain errors here 
       errorEmail = new ErrorEmail(); 
       foreach (string err in errors) 
       { 
        // add error info to message 
       } 
       errors.Clear(); 
       trigger = 0; 
      } 
     } 
     if (errorEmail != null) 
     { 
      // send message outside the lock 
      Send(errorEmail); 
     } 
    } 
} 
0

如果你跟踪你使用数据库发送的每封电子邮件,你可以随时轮询数据库以查看在给定的时间段内你看到了多少封给定的错误邮件。在少数我一直在努力的项目是在哪里发送电子邮件是必需的,发送的电子邮件的记录一直是姐妹的需求,从而为您的问题创建了一个解决方案。

+0

您可以使用嵌入式数据库,如SQLite(http://sqlite.phxsoftware.com/) – Tony 2010-10-01 13:15:49

0

使用将错误保存在列表中,然后使用System.Threading.Timer

传递包装SendEmail方法的委托。