Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use AsyncController or Task or Thread during time consuming operation in MVC?

I have a simple yet time consuming operation: when the user clicks a button, it performs a database intensive operation, processing records from an import table into multiple other tables, one import record at a time. I have a View with a button that triggers the operation and at the end of the operation a report is displayed.

I am looking at ways to notify the user that the operation is being processed.Here is a solution that I liked.

I have been reading up online about Asynchronous operations in MVC. I have found a numbers of links saying that if your process is CPU bound stick to using synchronous operations. Is database related process considered CPU bound or not?

Also if I got the Asynchronous operation route should I use AsyncController as described here or just use Task as in the example I mentioned and also here . or are they all the same?

like image 913
superartsy Avatar asked Feb 19 '13 21:02

superartsy


1 Answers

The first thing you need to know is that async doesn't change the HTTP protocol. As I describe on my blog, the HTTP protocol gives you one response for each request. So you can't return once saying it's "in progress" and return again later saying it's "completed".

The easy solution is to only return when it's completed, and just use AJAX to toss up some "in progress..." notification on the client side, updating the page when the request completes. If you want to get more complex, you can use something like SignalR to have the server notify the client when the request is completed.

In particular, an async MVC action does not return "early"; ASP.NET will wait until all the asynchronous actions are complete, and then send the response. async code on the server side is all about scalability, not responsiveness.

That said, I do usually recommend asynchronous code on the server side. The one exception is if you only have a single DB backend (discussed well in this blog post). If your backend is a DB cluster or a distributed/NoSQL/SQL Azure DB, then you should consider making it asynchronous.

If you do decide to make your servers asynchronous, just return Tasks; AsyncController is just around for backwards compatibility these days.

like image 85
Stephen Cleary Avatar answered Nov 15 '22 04:11

Stephen Cleary