How to use AsyncController or a task or thread during continuous operation in MVC?

I have a simple but time-consuming operation: when a user clicks a button, he performs an intensive database operation, processes records from the import table into several other tables, one import record at a time. I have a view with a button that starts the operation, and a report is displayed at the end of the operation.

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

I read online about asynchronous operations in MVC. I found some links saying that if your process is CPU related, use synchronous operations. Is the database related process a processed processor or not?

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

+5
source share
3 answers

The first thing you need to know is that asyncthe HTTP protocol does not change . As I describe on my blog, the HTTP protocol gives you one response for each request. Therefore, you cannot return by saying this “in the process” and you will return again, saying that it is “completed”.

, , AJAX , "in progress..." , . , - SignalR, .

, async MVC ""; ASP.NET , . async - , .

, . - ( ). - /NoSQL/SQL Azure DB, .

, Task s; AsyncController .

+2

, # 5.0, :

// A method to get your intensive dataset
public async Task<IntensiveDataSet> GetIntensiveDataSet() {
   //in here you'll want to use any of the newer await Async calls you find 
   // available for your operations. This prevents thread blocking.

    var intensiveDataSet = new IntensiveData();
    using (var sqlCommand = new SqlCommand(SqlStatement, sqlConnection))
        {
            using (var sqlDataReader = await sqlCommand.ExecuteReaderAsync())
            {
                while (await sqlDataReader.ReadAsync())
                {
                    //build out your intensive data set.
                }
            }
        }
    return intensiveDataSet;
}


// Then in your controller, some method that uses that:
public async Task<JsonResult> Intense() {
    return Json(await GetIntensiveDataSet());
}

JS ( JQuery):

$.get('/ControllerName/Intense').success(function(data) {
   console.log(data);
});

, - , .

- , ... , JsonResult, Session JQuery . , . " ".

+3

AJAX. "... " ,

$.ajax({
    url: @Url.Action("ActionName"),
    data: data
}).done(function(data) {
    alert('Operation Complete!');
});

alert('Operation Started');

// Display processing animation

, .

0

All Articles