异步和等待关键字行为 [英] async and await keywords behaviour

查看:79
本文介绍了异步和等待关键字行为的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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


这篇关于异步和等待关键字行为的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆