我有必须定期轮询外部资源的代码。简化后,它看起来像:
CancellationTokenSource cancellationSource = new CancellationTokenSource();
Task t = Task.Factory.StartNew(() =>
{
while (!cancellationSource.IsCancellationRequested)
{
Console.WriteLine("Fairly complex polling logic here.");
// Finishes sleeping before checking for cancellation request
Thread.Sleep(10000);
}
},
cancellationSource.Token);
如何以这样的方式对 10 秒延迟进行编码,以便在调用 cancelSource.Cancel() 时将其中断?