One of the reasons why it is important to use asynchronous programming, when our application relies on external services, is to allow ASP.NET to use I / O completion ports rather than blocking a thread waiting for an external service response, ASP.NET can park execution in the I / O completion port and use the thread to participate in another request, whenever the external service responds, then ASP.NET again executes this execution and resumes it. Thus, the thread is not a block.
An example of an asynchronous method:
[HttpPost]
public async Task<ActionResult> Open(String key)
{
Foo foo= await _externalService.GetFoo(key);
return View(foo);
}
But what happens if we use several requests to external services? How does ASP.NET handle this?
[HttpPost]
public async Task<ActionResult> Open()
{
List<Task<Foo>> tasks = new List<Task<Foo>>();
foreach (var key in this.Request.Form.AllKeys)
tasks.Add(_externalService.GetFoo(key));
var foos = await Task.WhenAll(tasks);
Foo foo = null;
foreach (var f in foos)
{
if (foo == null && f != null)
foo = f;
else
foo.Merge(f);
}
return View(foo);
}
-? , Task.WhenAll ?