我正嘗試在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 timer和 Best Timer for using in a Windows service
但是這些解決方案似乎並沒有解決我的問題。
歡迎任何建議!
我強烈建議你不要使用'System.Timers.Timer',因爲它會吞噬異常,隱藏錯誤。如果您的Elapsed事件發生異常,您永遠不會知道。請參閱http:// blog。mischel.com/2011/05/19/swallowing-exceptions-is-hiding-bugs/。你應該1)用'try/catch'保護你的事件處理程序,2)使用'System.Threading.Timer'。 –
@JimMischel我剛剛發現這實際上是我的問題,現在我看到您的評論。它只是吞下一個例外,因爲它沒有奏效。 System.Threading.Timer是否修復了這一切? –
'System.Threading.Timer'不會吞下異常,這會讓您知道您的處理程序中有問題。真正的解決方案是非常小心地處理你的定時器事件處理程序中的異常。 –