[RESOLVED]async methods in async controller

Can I use async actions in the AsyncController object without errors?

Yes in fact.

The class should be derived from AsyncController.

The action method should be splitted into two. One with Async prefix and other with Completed prefix. The first one will initiate the call. Second one will be invoked during completion.

Sample code snippet:

public class PortalController : AsyncController {
    public void NewsAsync(string city) {

        AsyncManager.OutstandingOperations.Increment();
        NewsService newsService = new NewsService();
        newsService.GetHeadlinesCompleted += (sender, e) =>
        {
            AsyncManager.Parameters["headlines"] = e.Value;
            AsyncManager.OutstandingOperations.Decrement();
        };
        newsService.GetHeadlinesAsync(city);
    }

    public ActionResult NewsCompleted(string[] headlines) {
        return View("News", new ViewStringModel
        {
            NewsHeadlines = headlines
        });
    }
}

Reference:
Using an Asynchronous Controller in ASP.NET MVC
 

You can also use async await pattern as per this article, if you are using .NET 4.5, VS 2012+:

http://www.asp.net/mvc/overview/performance/using-asynchronous-methods-in-aspnet-mvc-4

Snippet:

public async Task<ActionResult> GizmosAsync()
{
    ViewBag.SyncOrAsync = "Asynchronous";
    var gizmoService = new GizmoService();
    return View("Gizmos", await gizmoService.GetGizmosAsync());
}

Note:

1. The method has async keyword,
2. Method name suffixed with Async (though this suffix is not mandatory),
3. return type sorrounds Task<something>,
4. await keyword is used for the long running method. 

Leave a Reply