質問

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?

役に立ちましたか?

解決

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

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top