2010-10-01 21 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方法的委託。