How background worker usage in ASP.NET Core resuce load time

T.Zacks 3,986 Reputation points
2022-08-30T18:17:52.267+00:00

i have read this article https://blog.elmah.io/async-processing-of-long-running-tasks-in-asp-net-core/

first this article simulate a long running operation like

public async Task<IActionResult> Index()  
{  
    await CallSlowApi();  
    return View();  
}  
  
private async Task CallSlowApi()  
{  
    _logger.LogInformation($"Starting at {DateTime.UtcNow.TimeOfDay}");  
    await Task.Delay(10000);  
    _logger.LogInformation($"Done at {DateTime.UtcNow.TimeOfDay}");  
}  

with above approach page took 10 seconds and 30 milliseconds to load but the moment does the same job by ASP.NET Core background service then page took 13 milliseconds

i like to know how load reduce to 13 milliseconds ?

what these two line of code is doing ?

services.AddHostedService<LongRunningService>();  
services.AddSingleton<BackgroundWorkerQueue>();  

please some one help me to understand.

Thanks

ASP.NET Core
ASP.NET Core
A set of technologies in the .NET Framework for building web applications and XML web services.
4,164 questions
{count} votes

Accepted answer
  1. Bruce (SqlWork.com) 55,686 Reputation points
    2022-08-30T20:38:29.94+00:00

    the performance gain is by return the html before the long running task completes. while a background service is better management of threads, you could just:

     public IActionResult Index()   
     {   
         // start and don't wait   
         Thread.Run(() => CallSlowApi());   
       
         // return page -- the slowapi will complete after the html is returned   
         return View();   
     }   
    
    0 comments No comments

0 additional answers

Sort by: Most helpful