c# - ThrowIfCancellationRequested 带或不带异步/等待?

标签 c# asynchronous task .net-4.5

我有以下代码,运行时不会引发异常:

        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/

相关文章:

javascript - 异步:循环后回调

c# - 在非异步方法中返回异步任务的正确方法

c# - 没有时间的日期从和到过滤 c# mvc

c# - 类型化数据集可为空的日期值有问题

c# - 如何阻止用户在不禁用列表框中选择项目

java - 是否有用于计划或创建时间表的 Java API

c# - SSIS 无法创建此任务?

c# - 在 ASP.NET Core 中获取当前星期几

javascript - 如何让 Ajax 的某些部分同步发生,而前端逻辑异步发生?

java - Apache Camel : async operation and backpressure