I am working on a .NET Web API endpoint that will be called from a WPF client application. This endpoint needs to process a large amount of data sent from the WPF client. The client doesn’t need to wait for the processing to complete; it only needs to know that the request reached the API successfully.
Given that we have about 2,000 users using the WPF application, my goal is to ensure that the API endpoint quickly returns a 200 OK response to the client while triggering a long-running task to process the data. This way, the client doesn’t experience a delay while the server handles the background processing.
Here’s what I’ve done so far:
I have implemented the endpoint in a Web API controller.
I have set up logging and exception handling for the long-running task.
I am considering using a HostedService for background processing.
However, I’m facing a challenge with HostedService. It only takes a CancellationToken as a parameter for the ExecuteAsync method, but I need to pass the data that the endpoint receives to the background service for processing.
Could you suggest the best way to implement this pattern? Specifically:
How can I create a background service that can receive data from the API endpoint?
What are the limitations of this approach, and are there better alternatives for this kind of requirement?
Thank you in advance for your help!
[HttpPost]
public async Task<ActionResult> SubmitOrder([FromBody] List<Order> orders)
{
await _transactionProcessor.CreateOrders(orders); // this is the long running task
return Ok();
}
The processor
public class TransactionProcessor : ITractionProcessor
{
public async Task<TransactionResponse> CreateOrders(List<Order> orders)
{
await Task.Delay(5000);
// process orders that takes large amount of time.
throw new NotImplementedException();
}
}