Asynchronous methods of ApiController -- what's the profit? When to use?

18,055

Solution 1

I think the key misunderstanding is around how async tasks work. I have an async intro on my blog that may help.

In particular, a Task returned by an async method does not run any code. Rather, it is just a convenient way to notify callers of the result of that method. The MSDN docs you quoted only apply to tasks that actually run code, e.g., Task.Run.

BTW, the poster you referenced has nothing to do with threads. Here's what happens in an async database request (slightly simplified):

  1. Request is accepted by IIS and passed to ASP.NET.
  2. ASP.NET takes one of its thread pool threads and assigns it to that request.
  3. WebApi creates DataController etc.
  4. The controller action starts an asynchronous SQL query.
  5. The request thread returns to the thread pool. There are now no threads processing the request.
  6. When the result arrives from the SQL server, a thread pool thread reads the response.
  7. That thread pool thread notifies the request that it is ready to continue processing.
  8. Since ASP.NET knows that no other threads are handling that request, it just assigns that same thread the request so it can finish it off directly.

If you want some proof-of-concept code, I have an old Gist that artificially restricts the ASP.NET thread pool to the number of cores (which is its minimum setting) and then does N+1 synchronous and asynchronous requests. That code just does a delay for a second instead of contacting a SQL server, but the general principle is the same.

Solution 2

The profit of asynchronous actions is that while the controller is waiting for the sql query to finish no threads are allocated for this request, while if you used a synchronous method a thread would be locked up in the execution of this method from the start to end of that method. While SQL server is doing its job the thread isn't doing anything but waiting. If you use asynchronous methods this same thread can respond to other requests while SQL server is doing its thing.

I believe your steps are wrong at step 4, I don't think it will create a new thread to do the SQL query. At 6 there isn't created a new thread, it is just one of the available threads that will be used to continue from where the first thread left off. The thread at 6 could be the same as started the async operation.

Solution 3

I my opinion the following describes a clear advantage of async controllers over synchronous ones.

A web application using synchronous methods to service high latency calls where the thread pool grows to the .NET 4.5 default maximum of 5, 000 threads would consume approximately 5 GB more memory than an application able the service the same requests using asynchronous methods and only 50 threads. When you’re doing asynchronous work, you’re not always using a thread. For example, when you make an asynchronous web service request, ASP.NET will not be using any threads between the async method call and the await. Using the thread pool to service requests with high latency can lead to a large memory footprint and poor utilization of the server hardware.

from Using Asynchronous Methods in ASP.NET MVC 4

Solution 4

The point of async is not to make an application multi threaded but rather to let a single threaded application carry on with something different instead of waiting for a response from an external call that is executing on a different thread or process.

Consider a desk top application that shows stock prices from different exchanges. The application needs to make a couple of REST / http calls to get some data from each of the remote stock exchange servers.

A single threaded application would make the first call, wait doing nothing until it got the first set of prices, update it's window, then make a call to the next external stock price server, again wait doing nothing until it got the prices, update it's window... etc..

We could go all multi threaded kick off the requests in parallel and update the screen in parallel, but since most of the time is spent waiting for a response from the remote server this seems overkill.

It might be better for the thread to: Make a request for the first server but instead of waiting for the answer leave a marker, a place to come back to when the prices arrive and move on to issuing the second request, again leaving a marker of a place to come back to...etc.

When all the requests have been issued the application execution thread can go on to dealing with user input or what ever is required.

Now when a response from one of the servers is received the thread can be directed to continue from the marker it laid down previously and update the window.

All of the above could have been coded long hand, single threaded, but was so horrendous going multi threaded was often easier. Now the process of leaving the marker and coming back is done by the compiler when we write async/await. All single threaded.

There are two key points here:

1) Multi threaded does still happen! The processing of our request for stock prices happens on a different thread (on a different machine). If we were doing db access the same would be true. In examples where the wait is for a timer, the timer runs on a different thread. Our application though is single threaded, the execution point just jumps around (in a controlled manner) while external threads execute

2) We lose the benefit of async execution as soon as the application requires an async operation to complete. Consider an application showing the price of coffee from two exchanges, the application could initiate the requests and update it's windows asynchronously on a single thread, but now if the application also calculated the difference in price between two exchanges it would have to wait for the async calls to complete. This is forced on us because an async method (such as one we might write to call an exchange for a stock price) does not return the stock price but a Task, which can be thought of as a way to get back to the marker that was laid down so the function can complete and return the stock price.

This means that every function that calls an async function needs to be async or to wait for the "other thread/process/machine" call at the bottom of the call stack to complete, and if we are waiting for the bottom call to complete well why bother with async at all?

When writing a web api, IIS or other host is the desktop application, we write our controller methods async so that the host can execute other methods on our thread to service other requests while our code is waiting for a response from work on a different thread/process/machine.

Share:
18,055

Related videos on Youtube

Rustem Mustafin
Author by

Rustem Mustafin

Updated on June 21, 2022

Comments

  • Rustem Mustafin
    Rustem Mustafin almost 2 years

    (This probably duplicates the question ASP.NET MVC4 Async controller - Why to use?, but about webapi, and I do not agree with answers in there)

    Suppose I have a long running SQL request. Its data should be than serialized to JSON and sent to browser (as a response for xhr request). Sample code:

    public class DataController : ApiController
    {
        public Task<Data> Get()
        {
            return LoadDataAsync(); // Load data asynchronously?
        }
    }
    

    What actually happens when I do $.getJson('api/data', ...) (see this poster http://www.asp.net/posters/web-api/ASP.NET-Web-API-Poster.pdf):

    1. [IIS] Request is accepted by IIS.
    2. [IIS] IIS waits for one thread [THREAD] from the managed pool (http://msdn.microsoft.com/en-us/library/0ka9477y(v=vs.110).aspx) and starts work in it.
    3. [THREAD] Webapi Creates new DataController object in that thread, and other classes.
    4. [THREAD] Uses task-parallel lib to start a sql-query in [THREAD2]
    5. [THREAD] goes back to managed pool, ready for other processing
    6. [THREAD2] works with sql driver, reads data as it ready and invokes [THREAD3] to reply for xhr request
    7. [THREAD3] sends response.

    Please, feel free to correct me, if there's something wrong.

    In the question above, they say, the point and profit is, that [THREAD2] is not from The Managed Pool, however MSDN article (link above) says that

    By default, parallel library types like Task and Task<TResult> use thread pool threads to run tasks.

    So I make a conclusion, that all THREE THREADS are from managed pool.

    Furthermore, if I used synchronous method, I would still keep my server responsive, using only one thread (from the precious thread pool).

    So, what's the actual point of swapping from 1 thread to 3 threads? Why not just maximize threads in thread pool?

    Are there any clearly useful ways of using async controllers?

  • Rustem Mustafin
    Rustem Mustafin over 10 years
    So, I can write an application, that can start two simultaneous sql queries, print their results, and will not use more than one thread at any time? I would like to see the proof of concept for this answer. Links or code.
  • Rustem Mustafin
    Rustem Mustafin over 10 years
    "When the result arrives from the SQL server, a thread pool thread reads the response" -- can you elaborate on this? Where does the result arrive? Who invokes a thread from threadpool?
  • Stephen Cleary
    Stephen Cleary over 10 years
    Assuming that your SQL connection is using TCP/IP, the result arrives as a network packet. This triggers an interrupt, where the device driver reads the packet and passes it to user mode. The IOCP mechanism notifies the thread pool that a socket read completed, and it will ensure the response is complete, parse it, and then notify the request that it is ready to continue. (This is still slightly simplified).
  • Rustem Mustafin
    Rustem Mustafin over 10 years
    I am particularly interested in "notifies the thread pool that ..." AFAIK, when something can be notified -- it is either waiting for notifications, or periodically checks notification queue. I make a conclusion, that there is 1+ dedicated thread, for performing this operations. Is that correct? Should we count in that thread as a "wasted-because-of-async" resource?
  • Stephen Cleary
    Stephen Cleary over 10 years
    Not really, because IOCP thread(s) are shared, are only used very briefly, and exist even when you don't do asynchronous I/O. It's like the finalizer thread; you can't really say that there's a "wasted" thread used by that asynchronous operation, any more than you could say that there's a "wasted" thread used to wait for a finalizable object to be garbage collected. There's a finalizer thread, but it's shared, just like IOCP. More info here.
  • cmart
    cmart over 9 years
    Thx. What i would be interested in is: How was this done prior to async webapi action methods so that there is no thread waiting to process the request?
  • Stephen Cleary
    Stephen Cleary over 9 years
    @MarChr: ASP.NET has supported asynchronous modules and handlers for a very long time. Generally they used the APM (asynchronous programming model).