asp.netmultithreadingtask-parallel-libraryasync-awaitio-completion-ports

Asynchronous action methods and IO completion ports


One of the reasons why it is important to use asynchronous programming when our application relies on external services, is to allow ASP.NET the use of IO completion ports, so rather than block a thread waiting for the external service to respond, ASP.NET can park the execution in an IO completion port and use the thread for attending another request, whenever the external service responds, then ASP.NET gets that execution again and resumes it. This way, no thread is block.

A example of asynchronous method would be:

[HttpPost]
public async Task<ActionResult> Open(String key)
{
    Foo foo= await _externalService.GetFoo(key);
    return View(foo);
}

But what does happen if we use multiple requests to external services? How does ASP.NET handles it?

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

Is it still using IO completion ports? Or because the Task.WhenAll is blocking a thread?


Solution

  • It still uses I/O completion ports. WhenAll is asynchronous and does not block a thread.