异步和等待关键字行为 [英] async and await keywords behaviour
问题描述
class AsyncAndAwaitProgram
{
static void Main(string [] args)
{
Method1( );
Console.Read();
}
private static async void Method1()
{
await Task.Run(new Action(Method2));
Console.WriteLine(方法1);
}
private static async void Method2()
{
await task.Run(new Action(Method3));
Console。 WriteLine(方法2);
}
private static void Method3()
{
控制台。 WriteLine(方法3);
}
}
我期待输出为
方法3
方法2
方法1
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
推荐答案
你可能会期待输出,但它不是你会得到的。
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");
}
这篇关于异步和等待关键字行为的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!