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.
This is what the ConfigureAwait method enables to do. Calling ConfigureAwait(false) after the task means that we do not care if the code after the await, runs on the captured context or not. In the output console, “True” will be printed since the synchronization context is not kept.
ConfigureAwait in Action You capture the current context before awaiting the task, leaving it to the task context, then recovering (re-entering) it back when the task completes.
WhenAll(Task[])Creates a task that will complete when all of the Task objects in an array have completed.
Is it ok to use ConfigureAwait(false) only on the first await in my method and not on the rest? In general, no. See the previous FAQ. If the await task.
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); }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With