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:
- Windows 8 RTM
- .NET Framework 4.5
Sure. But since your
Dofunction creates a new task, it completes immediately, thus starting the nextDo. Remove the task creation fromDo(leaving only the Console.WriteLine stuff) and it should work as expected.