Asynchronous action methods and IO completion ports
Asked Answered
F

1

5

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?

Fallon answered 28/1, 2014 at 15:40 Comment(0)
T
7

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

Thermos answered 28/1, 2014 at 15:59 Comment(2)
I edited the question. It does not block "the" thread, but does it block any thread? I mean, my understanding is that I/O completion ports allow you to park a task without blocking a thread since there is an associated I/O operation. But in the case of 'WhenAll', how does it work?Fallon
WhenAll is just a TaskCompletionSource with a counter. When you call it, it sets the counter to the number of tasks and attaches a continuation to each task that decrements the counter. When the counter reaches zero, the TCS is completed, which allows your method to continue. No threads are blocked.Thermos

© 2022 - 2024 — McMap. All rights reserved.