[英]blocking timer in windows service
我目前在Windows服務中使用這個'計時器代碼':
var autoEvent = new AutoResetEvent(false);
Timer = new Timer(DoWork, autoEvent, 0, TimeInMilliSeconds);
我只是想知道如果DoWork尚未完成,是否可以阻止調用DoWork? 換句話說,如果TimeInMilliSeconds比執行DoWork所需的時間短?
如果我理解正確,那么您可以阻止自動回調並在需要時更改計時器。
Timer = new Timer(DoWork, autoEvent, 0, Timeout.Infinite);//Prevent periodic timer
void DoWork(object state)
{
//Do work and then set timer again
timer.Change(TimeInMilliSeconds, Timeout.Infinite);
}
不要忘記添加try/finally
塊,如果不這樣做,在異常的情況下不會再次調用你的計時器。
你可以完全避免使用計時器。 在我的程序中,我在OnStop和OnPause方法中設置了停止和暫停事件。 它們在OnStart和OnContinue方法中被清除。 在這個例子中,我在循環之間等待30秒。
WaitHandle[] waitFor = new WaitHandle[]{stopEvent, pauseEvent};
int trigger = -1;
bool keepGoing = true;
while(keepGoing)
{
trigger = WaitHandle.WaitAny(waitFor, TimeSpan.FromSeconds(30));
switch (trigger) {
case WaitHandle.WaitTimeout:
The main body of the loop goes here
break;
case 0: // stop
keepGoing = false;
break;
case 1: // pause
System.Diagnostics.Debug.Write("Paused - ");
System.Diagnostics.Debug.WriteLine(DateTime.Now.ToString());
break;
}
編輯如另一張海報的評論中所述,這需要與您的主要服務分開。 否則,您將永遠不會處理停止,暫停或恢復事件。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.