Reputation: 4759
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
Reputation: 1977
Microsoft suggests the following options in ASP.NET Core Performance Best Practices docs:
Upvotes: 4
Reputation: 180908
Since ASP.NET MVC does not itself provide the ability to process long-running tasks, you have to create an external solution.
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.
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.
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