Onu*_*nur 52 c# sleep .net-4.0 cancellation cancellationtokensource
什么是睡了一定的时间,但能够被一个中断的最佳方式IsCancellationRequested从CancellationToken?
我正在寻找一个适用于.NET 4.0的解决方案.
我想写
void MyFunc (CancellationToken ct)
{
//...
// simulate some long lasting operation that should be cancelable
Thread.Sleep(TimeSpan.FromMilliseconds(10000), ct);
}
Run Code Online (Sandbox Code Playgroud)
Fro*_*ode 108
我刚刚在这里写博客:
CancellationToken和Thread.Sleep
简而言之:
var cancelled = token.WaitHandle.WaitOne(TimeSpan.FromSeconds(5));
Run Code Online (Sandbox Code Playgroud)
在您的上下文中:
void MyFunc (CancellationToken ct)
{
//...
// simulate some long lasting operation that should be cancelable
var cancelled = ct.WaitHandle.WaitOne(TimeSpan.FromSeconds(10));
}
Run Code Online (Sandbox Code Playgroud)
或者,我认为这很清楚:
Task.Delay(waitTimeInMs, cancellationToken).Wait(cancellationToken);