Task.ContinueWith () the parent task does not wait for the completion of the child task

Since I understood Task in the context of a nested task, I really don't understand this. Why is the 3rd seal before the 2nd seal?

Even though I used Task.WaitAll(t) , it prints the 3rd line before the 2nd line.

The code:

 public static void Main() { Task t = new Task( () => { Thread.Sleep(2000); Console.WriteLine("1st print..."); }); t.ContinueWith( x => { Thread.Sleep(2000); Console.WriteLine("2nd print..."); }, TaskContinuationOptions.OnlyOnRanToCompletion); t.Start(); Task.WaitAll(t); Console.WriteLine("3rd print..."); Console.Read(); } 

Conclusion:

enter image description here

+5
source share
3 answers

You also need to wait for the continuation:

 Task t2 = t.ContinueWith( /* .. */ ); Task.WaitAll(new [] { t, t2 } ); 
+5
source

You just waited for t , not to continue it. That is why this continuation will continue in the future. If it was not for Console.Read , it will never start until the process exits.

Task.WaitAll(t) equivalent to t.Wait() (which you should use instead, because it is more idiomatic).

Waiting for all continuations (possibly recursively) will lead to unintuitive behavior and lead to nonlocal effects. Remote parts of the program may affect your code.

+2
source

You make the assumption that he should wait for child tasks, but there is no reason to make such assumptions. From MSDN:

Task.WaitAll: awaits completion of all specified task objects execution.

And he does exactly what he says. ContinueWith does not change the length of the original task, it does not increase. It just executes right after.

0
source

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