How can I make my MediatR notification handler fire and forget?
My sample code:
public class BackupDatabase : INotification {}
public class BackupDatabaseNotificationHandler : INotificationHandler<BackupDatabase>
{
public async Task Handle(BackupDatabase notification, CancellationToken cancellationToken)
{
await Task.Delay(100000000);
}
}
public async Task<IActionResult> SomeAction()
{
await _mediator.Publish(new BackupDatabase());
return Json(true);
}
I know one way is to use the Task.Factory.StartNew, But is there another way?
Mediatr notification handlers are already fire and forget.
Another way to deal with this would be to queue a background task to do the work. Look at something like Hangfire and implement that in either a _mediator.Send() or _mediator.Publish() method.
Hangfire will give you the ability to monitor the background task and has the ability to automatically retry the task if required.
There are some other options if Hangfire isn't an option for you.
Hope this helps!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With