Sandeep Thomas
Sandeep Thomas

Reputation: 4759

Best way of calling a long running process asynchronously in .net core web api

I am trying to call a long running task from web api like this

    [HttpGet]
    public async Task<IActionResult> Get()
    {
        await Task.Run(()=>_report.TestFunctionAsync());
        
        return Accepted();

    }

And this is the task

    public async Task TestFunctionAsync()
    {
        ProcessStatus = 0;
        Task.Delay(TimeSpan.FromSeconds(30));
        ProcessStatus = 1;//wrting to DB
        Task.Delay(TimeSpan.FromSeconds(10));
        ProcessStatus = 2;//Fetching from Excel
        Task.Delay(TimeSpan.FromSeconds(20));
        ProcessStatus = 3;//Processing
        Task.Delay(TimeSpan.FromSeconds(50));
        ProcessStatus = 9;//Finished
    }

But when googling I found from UI perspective, its async and UI never be blocked. But its not the correct way.

So please suggest a better way of implementing this. Also is there is any way to understand what is the status of the asyn task (using the ProcessStatus property)

Upvotes: 0

Views: 10503

Answers (2)

Serg.ID
Serg.ID

Reputation: 1977

Microsoft suggests the following options in ASP.NET Core Performance Best Practices docs:

  • Handle long-running requests with background services. In ASP.NET Core, background tasks can be implemented as hosted services. A hosted service class with background task logic that implements the IHostedService interface.
  • Also, you can use an Azure Function to complete work out-of-process. This scenario is especially beneficial for CPU-intensive tasks.
  • To notify your clients using real-time communication options, such as SignalR, to communicate with clients asynchronously.

Upvotes: 4

Robert Harvey
Robert Harvey

Reputation: 180908

Since ASP.NET MVC does not itself provide the ability to process long-running tasks, you have to create an external solution.

  1. Create a Durable Queue in which to place your requests for long-running operations. RabbitMQ as an example. Alternatively, write your requests to a requests table in your data store/database.

  2. Create a Backend Service to execute your long-running tasks. It should read the requests from your Durable Queue or database table, and act on them accordingly. This can be a Windows Service, Linux Daemon or AWS Lambda, etc.

  3. Create a notification mechanism so that the UI can be notified when the task completes, such as a web socket connection or polling. Or, provide an endpoint on the ASP.NET Web API that allows your web page to retrieve task status.

Upvotes: 4

Related Questions