Şafak Gür
Şafak Gür

Reputation: 7345

Task.ContinueWith runs before the task finishes executing

In Main method of a console application:

Do().ContinueWith(t => Do())
    .ContinueWith(t => Do())
    .ContinueWith(t => Do());

Do is a method that returns Task:

var source = new CancellationTokenSource();
var token = source.Token;
return Task.Factory.StartNew(() =>
{
    Console.WriteLine("Inside " + _Counter);
    token.WaitHandle.WaitOne(1000);
    Console.WriteLine(_Counter++ + " is done");
}, token);

And _Counter is an integer field:

private static int _Counter = 1;

When I run, the result is this:

Inside 1
1 is done
Inside 2
Inside 2
Inside 2
2 is done
3 is done
4 is done

So let's assume I have a Task called t and an Action<Task> called a.
If I call t.ContinueWith(a), a should be called after t completes, right? And when a runs, that should mean whatever delegate t calls has ended.

What causes this result? Am I not getting something obvious here?
What I use:

Upvotes: 4

Views: 2790

Answers (1)

Kevin Gosse
Kevin Gosse

Reputation: 39007

If I call t.ContinueWith(a), a should be called after t completes, right?

Sure. But since your Do function creates a new task, it completes immediately, thus starting the next Do. Remove the task creation from Do (leaving only the Console.WriteLine stuff) and it should work as expected.

    static void Do()
    {
        Console.WriteLine("Inside " + _Counter);
        Thread.Sleep(1000);
        Console.WriteLine(_Counter + " is done");
    }

    static void Main(string[] args)
    {
        Task.Factory.StartNew(Do)
            .ContinueWith(t => Do())
            .ContinueWith(t => Do())
            .ContinueWith(t => Do());
    }

Upvotes: 7

Related Questions