Here is a sample code:
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();
The output is (the order does not matter):
Exception
Should not be executed. Task status = Canceled
Why was the second ContinueWith executed and how to prevent it?
The parentheses in your last call to ContinueWith
are wrong:
.ContinueWith(t =>
Console.WriteLine(
"Should not be executed. Task status = " + t.Status,
TaskContinuationOptions.NotOnCanceled));
TaskContinuationOptions.NotOnCanceled
is being passed as an argument to WriteLine
.
Fixed:
.ContinueWith(t =>
Console.WriteLine(
"Should not be executed. Task status = " + t.Status),
TaskContinuationOptions.NotOnCanceled);
Because typo, Ctrl + Shift + F1 it.
// 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);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.