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
await
s 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:
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");
}