How to process a task asynchronously without blocking user's response in .net core WebAPI?

Viewed 63

I have to do an update operation on an API where I am passing a request body which need to be pushed to Db(call it D2).The projects layers looks like this

Controller -> Service -> Repository

So

1.some logic here in service. 
2.Update the entity and return this response to the controller.
3.Now I am calling the Handler to do some operations

So all above steps are inside Update() method in command handler.

How do I make the Step 3 as async. Since I don't want to block the response which I have got from Step 2 and want to return it to the controller immedialtely.Meanwhile the Step 3 will continue its execution in background.

1 Answers

If you don't want to block the response back to the client, then there are a couple of options available to you.

The pitfalls of "Fire and Forget" are worth understanding - https://stackoverflow.com/a/36338190/1538039 - as, if you're not waiting for the piece of work to complete, how do you deal with errors? However, perhaps an approach like Hangfire could a way you'd handle this.

I'd probably let some other piece of logic handle this work. At step 2, I'd raise an event and send it on to a message queue - that's a quick operation we can perform synchronously to ensure we've got a copy of the work to do persisted. You can then have some other piece of work subscribe to and process the queue, which is happening outside of the web response so you can now perform retries/handle errors and any other transient logic.

Related