I'm relatively new to .NET Core and trying to get my head around async/await usage to help speed up a slow-loading page.
My original controller method looked like this:
public IActionResult Index()
{
//other code here
regionVM.listEvents = getEvents(regionCatID);
regionVM.listNews = getNews(regionCatID);
regionVM.listLIA = getLIA(regionCatID);
regionVM.listAwards = getAwards(regionCatID);
return View("/Views/Regions/Index.cshtml", regionVM);
}
getEvents, getNews, getLIA, and getAwards are all other methods within the same controller. The corresponding lists they populate in the view model are used to display four different areas in the view. This all populates properly, but is slow.
I read a lot of different articles and posts, but tried to update my code following this one in particular: How can I run both of these methods 'at the same time' in .NET 4.5?
My new method looked like this:
public async Task<IActionResult> Index()
{
//other code here
var eTask = Task.Run(() => getEvents(regionCatID));
var nTask = Task.Run(() => getNews(regionCatID));
var lTask = Task.Run(() => getLIA(regionCatID));
var aTask = Task.Run(() => getAwards(regionCatID));
regionVM.listEvents = await eTask;
regionVM.listNews = await nTask;
regionVM.listLIA = await lTask;
regionVM.listAwards = await aTask;
return View("/Views/Regions/Index.cshtml", regionVM);
}
This seemed to work and compiled without any errors, but now when the regions pages load it's sort of hit or miss whether the four areas actually populate in the view. For instance, sometimes the news area will be blank, when I know there are news items that should be populated and were populating with the old synchronous method.
Is the view loading before the tasks are done executing? Or am I going about this completely the wrong way? Thanks for any suggestions.