I have run into a strange behaviour using async and await. If I try to await a manually created task T1, that itself is supposed to await another task T2, the task T1 has already run to completion even if task T2 is still awaiting.
To illustrate the problem I have written some code. When I run 'task1' from this example, the output is:
task1 ran to completion updating...
When I instead run 'task2', the output is always:
updating... task2 ran to completion
Does anybody have an explanation why the first await expression doesn't depend on the inner await?
private void OnLoaded(object sender, RoutedEventArgs e)
{
var task1 = new Task(async () => await UpdateAfterDelay());
task1.Start();
await task1;
Console.WriteLine("task1 ran to completion");
var task2 = Task.Run(async () => await UpdateAfterDelay());
await task2;
Console.WriteLine("task2 ran to completion");
}
private async Task UpdateAfterDelay()
{
await Task.Delay(2000);
Console.WriteLine("updating...");
}