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

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

问题描述

考虑这一点,

 工作任务=新建任务(异步()=> {
    等待TaskEx.Delay(1000);
});
task.Start();
task.Wait();

调用task.Wait()不会等待任务完成和下一行立即执行,但如果我换异步拉姆达前pression成一个方法调用中,code按预期工作

 私有静态异步任务AwaitableMethod()
{
    等待TaskEx.Delay(1000);
}

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

 等待AwaitableMethod();


解决方案

在您的lambda例如,当你调用 task.Wait(),你正在等待新的任务所构造,而不是延迟任务返回。为了让您所需的延迟,你还需要等待所产生的任务:

 任务<任务>任务=新任务<任务>(异步()=> {
    等待Task.Delay(1000);
});
task.Start();
task.Wait();
task.Result.Wait();

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

  Func键<任务>任务异步=()=> {
    等待TaskEx.Delay(1000);
};
任务()等待()。

Consider this,

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

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

then (updated according comment from svick)

await AwaitableMethod(); 

解决方案

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();

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

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