取消任务并等待终止的选项

时间:2013-09-25 05:12:44

标签: c# .net task-parallel-library async-await

我需要取消待处理的任务,并在代码流可以继续之前等待终止。通常,我这样做:

if (this.task != null)
{
    this.taskCancellationTokenSource.Cancel();
    try
    {
        await this.task;
        // I don't need to know the result, just log it
        Debug.Print(this.task.Status.ToString());
    }
    catch (Exception e)
    {
        // I don't need to know the result, just log it
        Debug.Print(e.ToString());
    }
}

我刚刚意识到我可以在没有try/catch的情况下做同样的事情:

if (this.task != null)
{
    this.taskCancellationTokenSource.Cancel();
    await this.task.ContinueWith(
        // I don't need to know the result, just log it
        (t) => Debug.Print(((object)t.Exception ?? (object)t.Status).ToString()), 
        TaskContinuationOptions.ExecuteSynchronously)
}

我是否错过了任何我应该坚持第一种方法的理由?

1 个答案:

答案 0 :(得分:2)

  

我是否错过了任何我应该坚持第一种方法的理由?

有两个原因,我的头脑:

    默认情况下,
  1. ContinueWith将使用当前的调度程序,这可能会导致并发问题或令人惊讶的行为。
  2. 当您阅读t属性时,先前任务(示例中为AggregateException)将包含在Task.Exception中的任何异常。
  3. 我建议使用await代替ContinueWith,因为它在这两种情况下都有更合理的行为。 await将捕获当前上下文并使用它来安排延续,await不会在AggregateException中包含例外。

    如果您使用ContinueWith,则应始终明确指定TaskScheduler以继续运行。

相关问题