如何不继续已取消的任务

本文关键字:任务 取消 何不 继续 | 更新日期: 2023-09-27 18:06:22

下面是一个示例代码:

var task = Task.Factory.StartNew(() => { throw new Exception(); });
task.ContinueWith(t => Console.WriteLine("Exception"), TaskContinuationOptions.OnlyOnFaulted);
task.ContinueWith(t => Console.WriteLine("Success"), TaskContinuationOptions.NotOnFaulted)
    .ContinueWith(t => Console.WriteLine("Should not be executed. Task status = " + t.Status, TaskContinuationOptions.NotOnCanceled));
Console.ReadLine();  

输出如下(顺序无关):

异常

不应该被执行。任务状态=已取消

为什么第二个ContinueWith被执行,如何防止它?

如何不继续已取消的任务

最后一次调用ContinueWith的括号是错误的:

.ContinueWith(t =>
    Console.WriteLine(
        "Should not be executed. Task status = " + t.Status,
        TaskContinuationOptions.NotOnCanceled));

TaskContinuationOptions.NotOnCanceled作为参数传递给WriteLine

固定:

.ContinueWith(t =>
    Console.WriteLine(
        "Should not be executed. Task status = " + t.Status),
    TaskContinuationOptions.NotOnCanceled);

因为错误, Ctrl + 转变 + F1

// ContinueWith([NotNull] Action<Task> continuationAction)
// WriteLine([NotNull] string format, object arg0)
.ContinueWith(t => Console.WriteLine("Should not be executed. Task status = " + t.Status, TaskContinuationOptions.NotOnCanceled));
// ContinueWith([NotNull] Action<Task> continuationAction, TaskContinuationOptions continuationOptions)
// WriteLine(string value) 
.ContinueWith(t => Console.WriteLine("Should not be executed. Task status = " + t.Status), TaskContinuationOptions.NotOnCanceled);