这是一个示例代码:
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/