I have an Index
action in ASP.net MVC controller. This action, calls (among other things) a private action that do a count on a SQL table with large set of rows. Th
Instead of async, use Task.Run:
Task.Run(() => MethodToExecuteInBackground(methodParameters)).ConfigureAwait(false).GetAwaiter();
You will also need to remove the async modifier from your controller Index method.
Now your controller method will return immediately while MethodToExecuteInBackground
goes off and does some work in the background.
Be aware that this will tie up a thread-pool thread until MethodToExecuteInBackground
finishes.
Its async
call but one important thing to understand here is when you make your controller action async
in that case : thread(of asp.net thread pool) which handling request return to thread pool (asp.net request thread pool ).
That means it release thread of thead pool to handle more request (It means async controller action just help to handle more request it doesnt mean that it decrease your time of processing, It just make your server more responsive). once operation under async/await is get completed new thread from request thread pool does further processing.
If you want real async page i.e. want to make your page more responsive I suggest make call using .ajax()
function of jQuery or using ajax extesion available in Asp.net MVC.
This works. But is this really async?
It is async in the fact that once you query your database (which is an IO bound operation), you free the ASP.NET Thread-Pool thread instead of using it to block until the query finishes.
Async doesn't mean "Return this request to the caller, and i'll finish executing at a later time", which is somewhat what you're expecting. It doesn't break the HTTP request-response protocol. What you want isn't achieved by async.
If you want the request to complete immediately, you'll need to queue it on some background thread, and push the data to the client side once the operation is complete.