更新时间:2023-02-24 21:18:46
你可能会期待输出,但它不是你会得到的。Method2
启动一个新的任务
和立即将控制权返回给来电者。因为它返回void
,所以调用者无法知道async
方法何时真正完成。Method1
创建一个新任务,该任务将在Method2
时完成>返回,然后await
s任务
。由于Method2
在执行Method3
之前返回,此任务
将立即完成,Method1
将继续执行。async void
应该只用于***事件处理程序或者即发即弃方法。
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 [ ^ ]
更改async
方法返回a任务
代替:
You might be expecting that output, but it's not what you're going to get.Method2
starts a newTask
and immediately returns control to the caller. Since it returnsvoid
, there is no way for the caller to know when theasync
method has really completed.Method1
creates a new task which will be completed whenMethod2
returns, and thenawait
s thatTask
. SinceMethod2
returns beforeMethod3
has been executed, thisTask
will complete immediately, andMethod1
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 yourasync
methods to return aTask
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");
}