Click here to Skip to main content
15,912,292 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
class AsyncAndAwaitProgram
{
static void Main(string[] args)
{
Method1();
Console.Read();
}
private static async void Method1()
{
await Task.Run(new Action(Method2));
Console.WriteLine("Method 1");
}
private static async void Method2()
{
await task.Run(new Action(Method3));
Console.WriteLine("Method 2");
}
private static void Method3()
{
Console.WriteLine("Method 3");
}
}

I'm expecting output as
Method 3
Method 2
Method 1
Posted

1 solution

You might be expecting that output, but it's not what you're going to get.

Method2 starts a new Task and immediately returns control to the caller. Since it returns void, there is no way for the caller to know when the async method has really completed.

Method1 creates a new task which will be completed when Method2 returns, and then awaits that Task. Since Method2 returns before Method3 has been executed, this Task will complete immediately, and Method1 will continue executing.

async void should only ever be used for top-level event handlers or fire-and-forget methods.

http://channel9.msdn.com/Series/Three-Essential-Tips-for-Async/Tip-1-Async-void-is-for-top-level-event-handlers-only[^]
http://blogs.msdn.com/b/pfxteam/archive/2012/02/08/10265476.aspx[^]

Change your async methods to return a Task instead:
C#
static void Main(string[] args)
{
    Method1().Wait();
    Console.Read();
}

private static async Task Method1()
{
    await Method2();
    Console.WriteLine("Method 1");
}

private static async Task Method2()
{
    await Task.Run(new Action(Method3));
    Console.WriteLine("Method 2");
}

private static void Method3()
{
    Console.WriteLine("Method 3");
} 
 
Share this answer
 
v2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900