How not to continue the canceled task?

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

Output (order does not matter):

An exception

Should not be followed. Task Status = Canceled

Why was the second ContinueWith executed and how to prevent it?

+4
source share
2 answers

Because a typo, Ctrl+ Shift+ F1it.

// 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);
+1
source

The brackets in your last call ContinueWithare incorrect:

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

TaskContinuationOptions.NotOnCanceledpassed as an argument WriteLine.

Fixed

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

Source: https://habr.com/ru/post/1543101/


All Articles