5
votes

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);
}
2
Can you explain further what exactly you expect to happen, and what actually happens? - sinelaw
I would like the tasks found in the DB to load into the partial view one by one so the user isn't starring at a loading screen, at the moment it takes about 10 secs for just four tasks to load. I can provide more information if needed... - user2711252

2 Answers

4
votes

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.

0
votes

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 (i.e. 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: