在传递给Task.WhenAll()的任务上使用ConfigureAwait(false) [英] Using ConfigureAwait(false) on tasks passed in to Task.WhenAll() fails

查看:80
本文介绍了在传递给Task.WhenAll()的任务上使用ConfigureAwait(false)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试决定如何等待所有异步任务完成.

I'm trying to decide how to wait on all async tasks to complete.

这是我目前拥有的代码

[HttpGet]
public async Task<JsonResult> doAsyncStuff()
{
  var t1 = this.service1.task1();
  var t2 = this.service2.task2();
  var t3 = this.service3.task3();
  var t4 = this.service4.task4();

  await Task.WhenAll(t1,t2,t3,t4);
  return this.Json(new {redirect = true, href = Url.Action("Blah")}, JsonRequestBehavior.AllowGet);
}

我很确定同步上下文无关,所以我尝试了这个.

I'm pretty certain the synchronization context isn't relevant so I tried this.

[HttpGet]
public async Task<JsonResult> doAsyncStuff()
{
  var t1 = this.service1.task1().ConfigureAwait(false);
  var t2 = this.service2.task2().ConfigureAwait(false);
  var t3 = this.service3.task3().ConfigureAwait(false);
  var t4 = this.service4.task4().ConfigureAwait(false);

  await Task.WhenAll(t1,t2,t3,t4);
  return this.Json(new {redirect = true, href = Url.Action("Blah")}, JsonRequestBehavior.AllowGet);
}

现在的问题是Task.WhenAll包含无效的参数,因为它将不接受已配置的任务Awaiatables.

The problem is now Task.WhenAll has invalid arguments because it will not accept Configured Task Awaiatables.

所以Task.WhenAll需要被替换为

So Task.WhenAll needs to be replaced with this

await t1; await t2; await t3; await t4;

这对我来说似乎不正确,但实际上几乎每个人都对ConfigureAwait有话要说的是如果没有错误,请使用它".据我所知(我没有编写任务),它们不使用同步上下文,也不依赖于它.

This doesn't seem correct to me, yet virtually everywhere anyone has anything to say about ConfigureAwait it is "use it, if it doesn't error". And to my knowledge (I didn't write the tasks), they do not use the Synchronous Context, nor do they rely on it.

重要的是,我希望task1到task4同时运行,因为它们不依赖于上一个完成.结果,我不想在每个任务前都等待着.但是我不想在所有4个步骤完成后返回Json响应,这就是为什么我当前在当前代码中拥有await Task.WhenAll()的原因.

Important to note I'd like task1 through task4 to run at the same time since they don't rely on the previous one finishing. As a result I don't want await in front of each task. But I don't want to return the Json response until after all 4 complete which is why I currently have the await Task.WhenAll() in the current code.

推荐答案

在实际执行await时只需要ConfigureAwait,正确的格式就是

You only need ConfigureAwait when you actually perform the await, the correct form would be

[HttpGet]
public async Task<JsonResult> doAsyncStuff()
{
  var t1 = this.service1.task1();
  var t2 = this.service2.task2();
  var t3 = this.service3.task3();
  var t4 = this.service4.task4();

  await Task.WhenAll(t1,t2,t3,t4).ConfigureAwait(false);
  return this.Json(new {redirect = true, href = Url.Action("Blah")}, JsonRequestBehavior.AllowGet);
}

这篇关于在传递给Task.WhenAll()的任务上使用ConfigureAwait(false)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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