问题
Since I was understanding the Task
in context of nested task, I really don't understand that- Why the 3rd print before 2nd print?
Even though, I have used Task.WaitAll(t)
, it print 3rd line before 2nd line.
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();
}
Output:
回答1:
You need to wait for the continuation also:
Task t2 = t.ContinueWith( /* .. */ );
Task.WaitAll(new [] { t, t2 } );
回答2:
You only waited for t
, not for its continuation. That's why that continuation will run at some time in the future. If it weren't for the Console.Read
it might never run before the process has exited.
Task.WaitAll(t)
is equivalent to t.Wait()
(which you should use instead because it is more idiomatic).
Having it wait for all continuations (maybe recursively) would make for unintuitive behavior and have non-local effects. Remote parts of the program could influence your code.
回答3:
You make an assumption that it should wait for child tasks but there is no base to make such assumptions. From MSDN:
Task.WaitAll: Waits for all of the provided Task objects to complete execution.
And it does exactly what it says. The ContinueWith
doesn't change the length of original task, it doesn't become longer. It just executes right after.
来源:https://stackoverflow.com/questions/27689000/task-continuewith-parent-task-doesnt-wait-for-child-task-to-finish