因此,只要应用程序正在运行或请求取消,我的应用程序几乎需要连续执行操作(每次运行之间暂停10秒左右).它需要做的工作可能需要30秒.
是否更好地使用System.Timers.Timer并使用AutoReset确保它在前一个"tick"完成之前不执行操作.
或者我应该在LongRunning模式下使用带有取消令牌的常规任务,并且在其内部有一个常规的无限while循环调用在调用之间使用10秒Thread.Sleep执行工作的操作?至于async/await模型,我不确定它在这里是否合适,因为我没有任何工作的返回值.
CancellationTokenSource wtoken;
Task task;
void StopWork()
{
wtoken.Cancel();
try
{
task.Wait();
} catch(AggregateException) { }
}
void StartWork()
{
wtoken = new CancellationTokenSource();
task = Task.Factory.StartNew(() =>
{
while (true)
{
wtoken.Token.ThrowIfCancellationRequested();
DoWork();
Thread.Sleep(10000);
}
}, wtoken, TaskCreationOptions.LongRunning);
}
void DoWork()
{
// Some work that takes up to 30 seconds but isn't returning anything.
}
Run Code Online (Sandbox Code Playgroud)
或者只是在使用AutoReset属性时使用简单的计时器,并调用.Stop()取消它?