2013-05-15 133 views
2

我正嘗試在Windows服務中使用計時器。該服務能夠啓動和停止,並且在發生這種情況時我會向事件日誌寫入內容,這是有效的。我的問題是,我也想使用一個定時器,每次timeElapsed事件被觸發時,定時器都會繼續運行並向事件日誌寫入內容。在長時間運行的Windows服務中使用計時器

編輯:(我改變了代碼,因此定時器是一個場,但依然沒有結果,我所期望的,在事件日誌中沒有日誌項)

using System.Timers; 

初始化服務:

public Timer timer; 

    public MonitorService() 
    { 
     InitializeComponent(); 
     timer = new Timer(10000); 
     //Some code that really doesn't matter 
    } 

上啓動事件

protected override void OnStart(string[] args) 
    { 
     // Hook up the Elapsed event for the timer. 
     timer.Elapsed += new ElapsedEventHandler(OnTimedEvent); 
     timer.Enabled = true; 

     timer.Start(); 

     EventLogger.WriteEntry("Biztalk monitoring service started", EventLogEntryType.SuccessAudit); 

     // If the timer is declared in a long-running method, use 
     // KeepAlive to prevent garbage collection from occurring 
     // before the method ends. 
     // GC.KeepAlive(timer); 
    } 


    private int count =0; 

上定時事件: (這是什麼都不行,沒有寫入事件日誌條目每隔10秒,而我希望它做的事)

// Specify what you want to happen when the Elapsed event is 
    // raised. 
    private void OnTimedEvent(object source, ElapsedEventArgs e) 
    { 
     //Some other code that doesn't mather 
     count++; 
     EventLogger.WriteEntry(string.Format("TimerEvent has ran {0} times. Total time is: {1}", count, e.SignalTime), EventLogEntryType.Information); 
    } 

的上停止事件:

protected override void OnStop() 
    { 
     EventLogger.WriteEntry("Biztalk monitoring service stopped", EventLogEntryType.Warning); 
    } 

主要

對於那些誰不知道這是我在Program.cs的主要方法:

 ///<summary> 
    ///The main entry point for the application. 
    ///</summary> 
    static void Main() 
    { 
     var servicesToRun = new ServiceBase[] 
      { 
       new MonitorService() 
      }; 
     ServiceBase.Run(servicesToRun); 
    } 

已經要求?確實是的!

我知道的事實,這個問題在前面已經喜歡這裏問:Windows service with timerBest Timer for using in a Windows service

但是這些解決方案似乎並沒有解決我的問題。

歡迎任何建議!

+1

我強烈建議你不要使用'System.Timers.Timer',因爲它會吞噬異常,隱藏錯誤。如果您的Elapsed事件發生異常,您永遠不會知道。請參閱http:// blog。mischel.com/2011/05/19/swallowing-exceptions-is-hiding-bugs/。你應該1)用'try/catch'保護你的事件處理程序,2)使用'System.Threading.Timer'。 –

+0

@JimMischel我剛剛發現這實際上是我的問題,現在我看到您的評論。它只是吞下一個例外,因爲它沒有奏效。 System.Threading.Timer是否修復了這一切? –

+0

'System.Threading.Timer'不會吞下異常,這會讓您知道您的處理程序中有問題。真正的解決方案是非常小心地處理你的定時器事件處理程序中的異常。 –

回答

5

您的計時器在OnStart方法中是本地的。它不應該。它應該是你的服務類的一個字段,所以你不需要使用提示來欺騙垃圾收集器。

編輯: 您沒有指定您的using s。確保使用Timer您正在使用System.Timers.Timer,而不是System.Windows.Forms.Timer

+0

噢,你說得對,甚至沒有注意到,而專注於其他可能的錯誤的東西!去試試吧! –

+0

我用你的解決方案編輯了我的問題,但它仍然不起作用。 –

+0

我非常肯定我正在使用那個,我將它添加到我的問題 –

0

如果您想要在設定的時間段內記錄事件日誌(除了您正在使用的計時器已過去的事件),您可以使用服務級別的另一個計時器並註冊已過去的時間事件。在這種情況下,你可以記錄任何你想要的。

正如nvoigt所提到的,您應該將此計時器移至服務級別。