Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Task.ContinueWith() parent task doesn't wait for child task to finish [duplicate]

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:

enter image description here

like image 944
nunu Avatar asked Dec 29 '14 12:12

nunu


1 Answers

You need to wait for the continuation also:

Task t2 = t.ContinueWith( /* .. */ );
Task.WaitAll(new [] { t, t2 } );
like image 74
Jcl Avatar answered Nov 14 '22 21:11

Jcl