且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

异步和等待关键字行为

更新时间: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 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:
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");
}