When is it absolutely necessary for a controller to be async? Should all controllers be async or is it bad practice to make all of them async unless it is necessary. Just looking for some general guidelines.
1 Answers
It's never absolutely necessary for a controller to be async. Calls to controller methods will eventually return. However, it might be desirable to hand off a long-running task to a thread, so that the web server is not blocked for a long period of time.
I wouldn't bother making every controller asynchronous. There is some overhead involved in creating new threads; making every controller asynchronous might actually slow things down.
Use asynchronous action methods for long-running, non-CPU bound requests. This avoids blocking the Web server from performing work while the request is being processed. A typical use for the AsyncController class is long-running Web service calls.
http://msdn.microsoft.com/en-us/library/ee728598(v=vs.100).aspx

- 198,589
- 55
- 464
- 673
-
"However, it might be desirable to hand off a long-running task to a thread" - I actually would prefer to create some explicit mechanism for a worker thread or some parallel routine instead of just `async`hronously exiting the controller method and then hoping that my long-running task will be finished, and I can later check the results (most probably, launching a new web request, since the original has already returned, if it was truly async) – JustAMartin Jun 18 '19 at 14:25
-
Would the "long-running, non-CPU bound requests" include database calls? Basically every call in my web app has database calls. – spirc Aug 17 '19 at 01:53
-
1Yes, if those database calls are long-running. All of the CPU time takes place on the database server. – Robert Harvey Aug 17 '19 at 03:28