I don't understand why the following code executes .ContinueWith() before Task.Delay() has ended its execution.
static void Main(string[] args)
{
Task t = new Task(async () =>
{
Console.WriteLine("1 delaying");
await Task.Delay(2000);
Console.WriteLine("2 delayed");
});
t.Start();
t.ContinueWith(_ => Console.WriteLine("3 continue"));
Console.ReadKey();
}
Output is:
1 delaying
3 continue
2 delayed
But I was expecting that "3 continue" should be executed as last.
With Task.Run() it works as expected:
Task.Run(async () =>
{
Console.WriteLine("1 delaying");
await Task.Delay(2000);
Console.WriteLine("2 delayed");
})
.ContinueWith(_ => Console.WriteLine("3 continue"));
Console.ReadKey();
Results in:
1 delaying
2 delayed
3 continue
In my case, I have to create a Task and start it later. How can I achieve that a created Task awaits Task.Delay() without executing the next Task (.ContinueWith()) first?