MVC Example calling async business method

MVC Example calling async business method

Old forum URL:

richardb posted on Monday, February 23, 2015

Can anyone point me to an example of calling an asynchronous method on a business object from a controller in ASP.Net MVC 5?   Or just show me what the call would be and how the business object method is done.

Currently confused looking at the examples in ProjectTracker, and wondering if GetProjectList<EventHandler<DataPortalResult<ProjectList>> callback) is what I need.



richardb replied on Monday, February 23, 2015

Ok, so I may have finally answered my own question.  I was confused with the callback approach, but I understand that's for Silverlight and some other paltforms.  Now with .Net 4.5 we can use Task await approach.

My Business Object.

public async static Task<VehicleList> GetVehicleListAsync()
       return await DataPortal.FetchAsync<VehicleList>();

    public async static Task<VehicleList> GetVehicleListAsync(string name)
       return await DataPortal.FetchAsync<VehicleList>(name);


And my controller calls it like this;

ViewData.Model = await VehicleList.GetVehicleListAsync();


Or if I happended to need multiple(s) and did not have a "Getter" type business object....something like this;

          var vehicles1Task = VehicleList.GetVehicleListAsync();
          var vehicles2Task = VehicleList.GetVehicleListAsync();

          //have used same getListXXX method call for demo purposes.

          await Task.WhenAll(vehicles1Task, vehicles2Task);

          ViewData.Model = vehicles1Task.Result;
          ViewBag.Vehicles = vehicles2Task.Result;


ajj3085 replied on Monday, February 23, 2015

Yes, if you have async / await this is probably your best bet.  The other async support is the older methods of doing async in .Net.  I think there's like three async patterns now implemented in the .Net framework.

Copyright (c) Marimer LLC