c# - 如何不继续取消的任务?

标签 c# task-parallel-library

这是一个示例代码:

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();  

输出是(顺序无关紧要):

Exception

Should not be executed. Task status = Canceled

为什么执行第二个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);

关于c# - 如何不继续取消的任务?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24020489/

相关文章:

c# - 匿名方法如何省略参数列表?

c# - 如何在 C# TextBox 中允许诸如 Ctrl-A 和 Ctrl-Backspace 之类的东西

c# - 如何将代码添加到 C# 窗体中的退出按钮?

c# - C#中的虚拟继承

c# - 使用 MEF 的多线程 EF

c# - Parallel.ForEach 在与 BlockingCollection 集成时停止

c# - Asp.Net/C# Å 何时等于 A? (且 É 等于 E)

c# - 并行编程 : create a certain number of processes and related data/work

c# - async 和 await 关键字不会导致创建额外的线程?

c# - ASP.Net Controller Action 仅在任务完成后返回