简体   繁体   中英

Async Actions in ASP.NET MVC 4

I have a synchronous call which I need to convert to async, Im using the async/await key words but this only returns once the task has complete what I need to do is return the results to the UI one by one.

The scenario is I have a task list displayed to the user once they have authenticated however I would like the task to be loaded one at a time once they have been retrieved from the DB, here is my actionResult which puts together the search criteria to pre-filter the tasks:

public async Task<ActionResult> Index(string searchTerm = null, int page = 1)
{
    Shared.InitialiseCriteria(SearchCriteria);
    SearchCriteria.DepartmentID = DepartmentID;
    SearchCriteria.PageSize = 15;
    SearchCriteria.FreeText = searchTerm;

    var model = await DoStuff(SearchCriteria);

        if (Request.IsAjaxRequest())
        {
            return PartialView("_ConversationList", model);
        }
    return View(model);

 }

And here is the await task this calls GetConversation which essentially gets the tasks when the first task is found I need it to be loaded to the Index view :

private async Task<Result> DoStuff(CSearchCriteria SearchCriteria)
{

   return GetConversations(SearchCriteria);
}

The only purpose of async controller in ASP.NET MVC is to free IIS thread to manage some other requests while async operation is in progress. From caller perspective it is the same as if you are using sync controller.

So, I don't think that you can achieve what you want with async controller (you can use it but it will not solve your problem).

I think you can implement some sort of paging at server-side to retrieve portions of data and send it to client via SignalR .

There are a couple of issues here:

  • How to cause ASP.NET to start returning data as soon as each item is available,
  • How to coordinate the client & server, so that the client knows that a new item is available (ie so it can parse each item in the response separately, or so it can request more data if you're looking for 'pull')

As explained in AlexK's answer, the async api does not alter the way the server responds to the client. Async only allows for your app to free-up threads when they're not in use, and makes it easier to parallelize portions of requests that depend on multiple resources.

Besides using SignalR, which is designed for this, you can use the built-in lower-level mechanism - PushStreamContent - yourself. Here are a couple of blog posts on how to do that:

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM