can not await async lambda

kennyzx picture kennyzx · Oct 24, 2012 · Viewed 73.9k times · Source

Consider this,

Task task = new Task (async () =>{
    await TaskEx.Delay(1000);
});
task.Start();
task.Wait(); 

The call task.Wait() does not wait for the task completion and the next line is executed immediately, but if I wrap the async lambda expression into a method call, the code works as expected.

private static async Task AwaitableMethod()
{
    await TaskEx.Delay(1000);    
}

then (updated according comment from svick)

await AwaitableMethod(); 

Answer

Joe Daley picture Joe Daley · Oct 24, 2012

In your lambda example, when you call task.Wait(), you are waiting on the new Task that you constructed, not the delay Task that it returns. To get your desired delay, you would need to also wait on the resulting Task:

Task<Task> task = new Task<Task>(async () => {
    await Task.Delay(1000);
});
task.Start();
task.Wait(); 
task.Result.Wait();

You could avoid constructing a new Task, and just have one Task to deal with instead of two:

Func<Task> task = async () => {
    await TaskEx.Delay(1000);
};
task().Wait();