Say I have the following methods, in my ASP.NET 5 Web API:
//(in a different class)
public static async Task SendStatus(string message)
{
await SendStatusMessage(message); //sends a status message to the client
}
[HttpGet("api/dowork")]
public async Task<IActionResult> DoWork()
{
await SendStatusToClient("starting to do work!");
//when it reaches this point, it should run the code in the background
await DoTheActualWork();
await SendStatusToClient("finished work!");
//I want the control back after it starts running the above code in the background, to send a 200 status code
return Ok();
}
This is how it should run:
- It sends a status message, stating that it has started doing the work.
- It does the work, and after the work is done, sends a status message. All of this should be done in the background.
- Return a 200 (OK) status code to the user who requested the work. The actual work takes a significant amount of time and should still be running in the background.
How would I achieve this?
Answers:
Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.
Method 1
There are two answers helpful to you.
- The first one, how to do it: Webapi2 – Return from controller action after one task completes, but continue with further Async processing
- The second one, why not do it: How to answer a request but continue processing code in WebApi
So what to do now. I would suggest the following steps:
- Create a queue. Either a database table an azure service bus queue, a rabbitmq queue or even a simple file or just a static memory structure. (Production loads require some persistence though)
- Create a long running task to process the queued items. Web api supports background tasks, but you could create a service a job on the cloud or a windows service or any other application or service that works.
All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0