How to wait all tasks to finished before returning to a view?

Dondon510 221 Reputation points
2022-09-16T15:57:02.007+00:00

I have codes below, but looks like it returns to the view before all of the async tasks have been finished.

How to wait all tasks to finished before returning to a view?

public async Task<IActionResult> Learning01()  
{  
    JObject jo1 = await DoSales_Store1Async(param1);  
    JObject jo2 = await DoSales_Store2Async(param1);  
    JObject jo3 = await DoSales_Store3Async(param1);  
  
    JObject joData = JObject.FromObject(new  
    {  
       jo1 = jo1,  
       jo2 = jo2,  
       jo3 = jo3  
    }  
  
    return await Task.FromResult(Json(joData));  
}  
  
  
ASP.NET Core
ASP.NET Core
A set of technologies in the .NET Framework for building web applications and XML web services.
4,187 questions
{count} votes

3 answers

Sort by: Most helpful
  1. Dondon510 221 Reputation points
    2022-09-16T16:39:40.487+00:00

    @AgaveJoe
    yes, you are right!, I missed something there! my bad.
    thank you

    0 comments No comments

  2. Bruce (SqlWork.com) 56,686 Reputation points
    2022-09-16T16:58:55.707+00:00

    Also line 14 is just useless code. s/b:

    return Json(joData);

    0 comments No comments

  3. SurferOnWww 1,911 Reputation points
    2022-09-17T00:59:32.067+00:00

    It seems to me that async / wait used in your does not make sense. I suggest that you simply write it as follows:

    public IActionResult Learning01()  
    {  
        // CPU-bound tasks       
          
        return Json(joData);  
    }  
    

    The reasons are:

    Asynchronous Code Is Not a Silver Bullet
    https://learn.microsoft.com/en-us/archive/msdn-magazine/2014/october/async-programming-introduction-to-async-await-on-asp-net#asynchronous-code-is-not-a-silver-bullet

    "Async and await on ASP.NET are all about I/O. They really excel at reading and writing files, database records, and REST APIs. However, they’re not good for CPU-bound tasks. You can kick off some background work by awaiting Task.Run, but there’s no point in doing so. In fact, that will actually hurt your scalability by interfering with the ASP.NET thread pool heuristics. If you have CPU-bound work to do on ASP.NET, your best bet is to just execute it directly on the request thread. As a general rule, don’t queue work to the thread pool on ASP.NET."

    Avoid blocking calls
    https://learn.microsoft.com/en-us/aspnet/core/performance/performance-best-practices?view=aspnetcore-6.0#avoid-blocking-calls

    "ASP.NET Core already runs app code on normal Thread Pool threads, so calling Task.Run only results in extra unnecessary Thread Pool scheduling."