Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
534 views
in Technique[技术] by (71.8m points)

c# - Using ConfigureAwait(false) on tasks passed in to Task.WhenAll() fails

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

Here is the code I currently have

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

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

So Task.WhenAll needs to be replaced with this

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

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.

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...