我有以下代码,运行时不会引发异常:
var t = Task.Factory.StartNew(() => LongRunningMethod(cancellationToken, progress), cancellationToken);
t.ContinueWith(Callback, TaskScheduler.FromCurrentSynchronizationContext());
在“LongRunningMethod”内,我调用cancelToken.ThrowIfCancellationRequested()。回调将始终被调用(这就是我想要的),并且正确传递给回调的任务将 IsCancelled 设置为 true 或 false。
使用 async/await 关键字,我必须将上面的行修改为以下内容:
try
{
await Task.Factory.StartNew(() => LongRunningMethod(cancellationToken, progress), cancellationToken);
textEdit1.Text = "Done";
}
catch (OperationCanceledException)
{
textEdit1.Text = "Cancelled";
}
在这种情况下,为什么 ThrowIfCancellationRequested() 会抛出一个我需要捕获的实际异常?
最佳答案
使用 ContinueWith
,您将获得之前运行的 Task
,您可以询问它是否已取消 (Task.IsCancelled
) >)。使用await
,你就没有这个了。传达取消的唯一方法是通过异常。
现在,await
只是使用任务,因此您可以“插入”延续。例如:
await Task.Factory
.StartNew(() => LongRunningMethod(cancellationToken, progress), cancellationToken)
.ContinueWith(t=>Trace.WriteLine("Canceled"), TaskContinuationOptions.OnlyOnCanceled);
您仍然可以使用await,然后使用ContinueWith
来处理仅取消场景。因此,从技术上讲,await
正在等待继续。
关于c# - ThrowIfCancellationRequested 带或不带异步/等待?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11987881/