我正在尝试创建一个 Windows 服务,该服务每 5 分钟轮询一次系统并检查需要完成的某些操作。我已经阅读了WaitHandles
它们在这方面的用处,但需要了解它是如何工作的。
请参见下面的代码:
public partial class PollingService : ServiceBase
{
private CancellationTokenSource cancelToken = new CancellationTokenSource();
private Task mainTask = null;
public PollingService()
{
InitializeComponent();
}
protected override void OnStart(string[] args)
{
mainTask = new Task(pollInterval, cancelToken.Token, TaskCreationOptions.LongRunning);
mainTask.Start();
}
public void pollInterval()
{
CancellationToken cancel = cancelToken.Token;
TimeSpan interval = TimeSpan.FromMinutes(5);
while (!cancel.IsCancellationRequested && !cancel.WaitHandle.WaitOne(interval))
{
if (cancel.IsCancellationRequested)
{
break;
}
EventLog.WriteEntry("*-HEY MAN I'M POLLNG HERE!!-*");
//Polling code goes here. Checks periodically IsCancellationRequested
}
}
protected override void OnStop()
{
cancelToken.Cancel();
mainTask.Wait();
}
}
上面的代码似乎应该从我的研究中得到,但我不明白这!cancel.WaitHandle.WaitOne(interval)
部分。这如何让循环每五分钟等待一次?我需要了解这部分代码来完成我的脚本,或者知道我在使用 WaitHandle 时是否完全错误。