0

This might sound like a newbie question, but any help in pointing me in the right direction would be apprecited.

If I have a controller (.Net) that I want to run some database transactions (fetch and update), is there a way to do it so that I can return a response quickly to the client without having to wait for the database stuff to save first?

Like some kind of background service? Any pointer to a link would be appreciated

ex.

[HttpPost("update")]
public async Task<IActionResult> UpdateAccount(AccountDto accountDto) 
{
     var user = await _userManager.FindByEmailAsync(accountDto.Email);

     // edit the user and save to db, but don't wait for it to finish before returning OK()
     user.firstName = "test";
     user.lastName = "test";
     await _userManager.UpdateAsync(user);

     return Ok();
 }
chuckd
  • 13,460
  • 29
  • 152
  • 331
  • Does this answer your question? [Do some work after the response in ASP.NET Core](https://stackoverflow.com/questions/41667827/do-some-work-after-the-response-in-asp-net-core) – Christoph Lütjen Dec 16 '21 at 20:45
  • You can fire off background tasks with a tool like Hangfire for example, or use a message queueing system to fire off those changes to another service. But looking at the code above, I wouldn't bother for something so trivial. – DavidG Dec 16 '21 at 20:46
  • Alternatives: Background services es described here: https://learn.microsoft.com/en-us/aspnet/core/fundamentals/host/hosted-services?view=aspnetcore-6.0&tabs=visual-studio or hangfire https://www.hangfire.io/ or a queue like e.g. rabbitmq https://www.rabbitmq.com/ – Christoph Lütjen Dec 16 '21 at 20:48
  • 1
    Don't you care if the update failed or succeeded? I think that would be relevant to the user. – Ryan Wilson Dec 16 '21 at 20:50
  • @RyanWilson agreed. OP should ask themselves why they want this behavior. Sending back 200 when the request could fail, or have invalid request params, or any other fail case, it would be hard to tell where in the chain a problem is occurring. – TheBatman Dec 16 '21 at 21:28
  • Hi Ryan. Actually no, I don't care, because this controller is receiving webhooks from a 3rd party service. The response is only being sent to the service to acknowledge that I received it. – chuckd Dec 18 '21 at 04:16

0 Answers0