我有以下代码运行而不会引发异常:
var t = Task.Factory.StartNew(() => LongRunningMethod(cancellationToken, progress), cancellationToken);
t.ContinueWith(Callback, TaskScheduler.FromCurrentSynchronizationContext());
在“LongRunningMethod”中,我调用了cancellationToken.ThrowIfCancellationRequested()。回调将始终被调用(这是我想要的),并且正确传递给回调的任务将 IsCancelled 设置为 true 或 false。
使用 async/await 关键字,我必须将上述行修改为以下内容:
try
{
await Task.Factory.StartNew(() => LongRunningMethod(cancellationToken, progress), cancellationToken);
textEdit1.Text = "Done";
}
catch (OperationCanceledException)
{
textEdit1.Text = "Cancelled";
}
在这种情况下,为什么 ThrowIfCancellationRequested() 会引发我需要捕获的实际异常?