我正在寻找一种同步任务取消的方法。我有这样的任务:
public Task AddAsync(CancellationToken cancellationToken)
{
Task result = Task.Factory.StartNew(() =>
{
// So wait forever
var wait = new ManualResetEvent(false);
var waitIndex = WaitHandle.WaitAny(new[] { wait,
cancellationToken.WaitHandle});
switch (waitIndex)
{
case 0:
Debug.WriteLine("Everything fine");
break;
case 1:
Debug.WriteLine("Cancelled");
Thread.Sleep(5000);
cancellationToken.ThrowIfCancellationRequested();
break;
}
return;
}, cancellationToken);
return result;
}
异步方法将像这样调用:
var ts = new CancellationTokenSource();
var t = AddAsync(ts.Token);
if (!t.Wait(TimeSpan.FromSeconds(5)))
{
ts.Cancel();
}
所以在超时后我打电话取消,但任务需要一些时间才能取消。那么如何进行同步取消呼叫呢?