rnofenko rnofenko - 2 months ago 8
C# Question

How to wait for later started task

In my code sample main thread doesn't wait when task2 is finished.

public async Task Run()
{
Console.WriteLine("Main start");
await getTask1();
Console.WriteLine("Main 2");
var task2 = getTask2();
Console.WriteLine("Main 3");
task2.Start();
await task2;
Console.WriteLine("Main end");
}

private async Task getTask1()
{
Console.WriteLine("task1 start");
await Task.Delay(100);
Console.WriteLine("task1 end");
}

private Task getTask2()
{
return new Task(async () =>
{
Console.WriteLine("task2 start");
await Task.Delay(100);
Console.WriteLine("task2 end");
});
}


Result of execution this code is


Main start

task1 start

task1 end

Main 2

Main 3

task2 start

Main end

task2 end


How can I change code where 'Main end' will be at the end of list.

Answer

new Task( does not work with async functions by itself. You are creating a Task<Task>, you need to call Unwrap() before you await the inner task.

private Task<Task> getTask2()
{
    return new Task(async () =>
    {
        Console.WriteLine("task2 start");
        await Task.Delay(100);
        Console.WriteLine("task2 end");
    });
}

var task2 = getTask2();
Console.WriteLine("Main 3");
task2.Start();
await task2.Unwrap();
Comments