Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 699
vtortola Avatar asked Jan 28 '14 15:01

vtortola


1 Answers

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

like image 69
Stephen Cleary Avatar answered Oct 03 '22 22:10

Stephen Cleary