【发布时间】:2012-08-12 20:16:41
【问题描述】:
我有以下代码在运行时不会引发异常:
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() 会引发我需要捕获的实际异常?
【问题讨论】:
标签: c# asynchronous task .net-4.5