不能等待异步 lambda [英] can not await async lambda

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

问题描述

考虑一下,

Task task = new Task (async () =>{
    await TaskEx.Delay(1000);
});
task.Start();
task.Wait(); 

调用 task.Wait() 不会等待任务完成并立即执行下一行,但如果我将异步 lambda 表达式包装到方法调用中,代码会按预期工作.

The call task.Wait() does not wait for the task completion and the next line is executed immediately, but if I wrap the async lambda expression into a method call, the code works as expected.

private static async Task AwaitableMethod()
{
    await TaskEx.Delay(1000);    
}

然后(根据 svick 的评论更新)

then (updated according comment from svick)

await AwaitableMethod(); 

推荐答案

在您的 lambda 示例中,当您调用 task.Wait() 时,您正在等待您构造的新任务,而不是它返回的延迟任务.要获得所需的延迟,您还需要等待生成的任务:

In your lambda example, when you call task.Wait(), you are waiting on the new Task that you constructed, not the delay Task that it returns. To get your desired delay, you would need to also wait on the resulting Task:

Task<Task> task = new Task<Task>(async () => {
    await Task.Delay(1000);
});
task.Start();
task.Wait(); 
task.Result.Wait();

您可以避免构建一个新任务,而只需处理一个而不是两个任务:

You could avoid constructing a new Task, and just have one Task to deal with instead of two:

Func<Task> task = async () => {
    await TaskEx.Delay(1000);
};
task().Wait();

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

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