睡眠一定时间但又能被
IsCancellationRequested
的 CancellationToken
打断的最佳方法是什么?
我正在寻找适用于 .NET 4.0 的解决方案。
我想写
void MyFunc (CancellationToken ct)
{
//...
// simulate some long lasting operation that should be cancelable
Thread.Sleep(TimeSpan.FromMilliseconds(10000), ct);
}
我刚刚在这里写了博客:
CancellationToken 和 Thread.Sleep
简而言之:
var cancelled = token.WaitHandle.WaitOne(TimeSpan.FromSeconds(5));
根据您的情况:
void MyFunc (CancellationToken ct)
{
//...
// simulate some long lasting operation that should be cancelable
var cancelled = ct.WaitHandle.WaitOne(TimeSpan.FromSeconds(10));
}
或者,我认为这很清楚:
Task.Delay(waitTimeInMs, cancellationToken).Wait(cancellationToken);
要在一段时间后取消异步操作,同时仍然能够手动取消操作,请使用如下所示的内容
CancellationTokenSource cts = new CancellationTokenSource();
CancellationToken token = cts.Token;
cts.CancelAfter(5000);
这将导致五秒后取消。要取消您自己的操作,您只需将
token
传递到您的异步方法中并使用 token.ThrowifCancellationRequested()
方法,您已经在某处设置了一个事件处理程序来触发 cts.Cancel()
。
完整的例子是:
CancellationTokenSource cts = new CancellationTokenSource();
CancellationToken token = cts.Token;
cts.CancelAfter(5000);
// Set up the event handler on some button.
if (cancelSource != null)
{
cancelHandler = delegate
{
Cancel(cts);
};
stopButton.Click -= cancelHandler;
stopButton.Click += cancelHandler;
}
// Now launch the method.
SomeMethodAsync(token);
其中
stopButton
是您点击取消正在运行的任务的按钮
private void Cancel(CancellationTokenSource cts)
{
cts.Cancel();
}
该方法定义为
SomeMethodAsync(CancellationToken token)
{
Task t = Task.Factory.StartNew(() =>
{
msTimeout = 5000;
Pump(token);
}, token,
TaskCreationOptions.None,
TaskScheduler.Default);
}
现在,为了使您能够工作线程并启用用户取消,您需要编写一个“泵送”方法
int msTimeout;
bool timeLimitReached = false;
private void Pump(CancellationToken token)
{
DateTime now = DateTime.Now;
System.Timer t = new System.Timer(100);
t.Elapsed -= t_Elapsed;
t.Elapsed += t_Elapsed;
t.Start();
while(!timeLimitReached)
{
Thread.Sleep(250);
token.ThrowIfCancellationRequested();
}
}
void t_Elapsed(object sender, ElapsedEventArgs e)
{
TimeSpan elapsed = DateTime.Now - this.readyUpInitialised;
if (elapsed > msTimeout)
{
timeLimitReached = true;
t.Stop();
t.Dispose();
}
}
注意,
SomeAsyncMethod
将直接返回给调用者。要阻止呼叫者,您必须将 Task
在呼叫层次结构中向上移动。
在 CancellationTokenSource 被释放后访问 CancellationToken.WaitHandle 可能会抛出异常:
ObjectDisposeException:CancellationTokenSource 已被处置。
在某些情况下,尤其是当手动处理链接的取消源时(理应如此),这可能会很麻烦。
此扩展方法允许“安全取消等待”;但是,它应该与取消令牌的状态和/或返回值的使用的检查和正确标记结合使用。这是因为它抑制了访问 WaitHandle 的异常,并且返回速度可能比预期更快。
internal static class CancellationTokenExtensions
{
/// <summary>
/// Wait up to a given duration for a token to be cancelled.
/// Returns true if the token was cancelled within the duration
/// or the underlying cancellation token source has been disposed.
/// </summary>
public static bool WaitForCancellation(this CancellationToken token, TimeSpan duration)
{
WaitHandle handle;
try
{
handle = token.WaitHandle;
}
catch
{
/// The source of the token was disposed (already cancelled)
return true;
}
if (handle.WaitOne(duration))
{
/// A cancellation occured during the wait
return true;
}
else
{
/// No cancellation occured during the wait
return false;
}
}
}
到目前为止我找到的最好的解决方案是:
void MyFunc(CancellationToken ct)
{
//...
var timedOut = WaitHandle.WaitAny(new[] { ct.WaitHandle }, TimeSpan.FromMilliseconds(2000)) == WaitHandle.WaitTimeout;
var cancelled = ! timedOut;
}
更新:
迄今为止最好的解决方案是接受的答案。