Webapi 2 - how to correctly call a long async / method in a new thread and return a response to the client

I am developing a web-api that takes data from a client and saves it for later use. Now I have an external system that needs to know about all the events, so I want to configure the notification component in my web api.

What I do, after saving the data, I execute the SendNotification(message) method in my new component. In the meantime, I do not want my client to wait or even know that we are sending notifications, so I want to return 201 Created / 200 OK response to my clients as soon as possible.

Yes, this is a fire-and-forget scenario. I want the notification component to handle all cases of exception (if the notification fails, the api client does not care at all).

I tried using async/await , but this does not work in the web-api, because when the request stream completes, the async operation does it as well.

So, I took a look at Task.Run() .

My controller looks like this:

 public IHttpActionResult PostData([FromBody] Data data) { _dataService.saveData(data); //This could fail, and retry strategy takes time. Task.Run(() => _notificationHandler.SendNotification(new Message(data))); return CreatedAtRoute<object>(...); } 

And the method in my NotificationHandler

 public void SendNotification(Message message) { //..send stuff to a notification server somewhere, syncronously. } 

I'm relatively new in the C # world, and I don't know if there is a more elegant (or right) way to do this. Are there any pitfalls using this method?

+5
source share
2 answers

It really depends on how long. You have considered QueueBackgroundWorkItem as detailed here . If you want to realize a very fast fire and forget, you can also think of a queue to print these messages so that you can immediately return from the controller. Then you should have something that checks the queue and sends notifications, such as a scheduled task, a Windows service, etc. IIRC, if IIS recycles during the task, the process is killed, while QueueBackgroundWorkItem has a grace period for which ASP.NET will allow the workstation to exit.

+4
source

I would look at Hangfire . It is quite easy to configure, it should work in the ASP.NET process and can easily be transferred to a stand-alone process in case of a sudden increase in load on IIS. I experimented with Hangfire a while ago, but offline. It has enough documents and easily understands the API.

+1
source

Source: https://habr.com/ru/post/1243303/


All Articles