0

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.

coredev
  • 11
  • 3
  • [Background tasks with hosted services in ASP.NET Core](https://learn.microsoft.com/en-us/aspnet/core/fundamentals/host/hosted-services?view=aspnetcore-6.0&tabs=visual-studio) – Alexander Petrov Sep 11 '22 at 10:44
  • @AlexanderPetrov So I have created a backgroundService for the Step 3 handler.How do I trigger it just after Step 2 has completed ? – coredev Sep 12 '22 at 06:28

1 Answers1

1

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.

Dylan Morley
  • 1,656
  • 12
  • 21
  • So ,the async task(or the handler in step 3) which I am dealing with,is expected to return no response to users,and if something goes wrong ,should be gracefully handled without telling users what went wrong.Although it will log everything about what error have come – coredev Sep 11 '22 at 10:23
  • 1
    Your non-functional requirements should drive your approach. Is it acceptable if you lose any of this work? How high volume will you be operating at? Should you retry work until it succeeds? Either hangfire or a queue approach could handle what you mention, but a queue will help in higher volume scenarios (and, has a number of other advantages that would make it my starting point) – Dylan Morley Sep 11 '22 at 11:02