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) {
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?