Reputation: 679
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?
Upvotes: 4
Views: 555
Reputation: 10432
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);
Upvotes: 1
Reputation: 79601
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);
Upvotes: 2