4

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?

  • You should be very careful with phrasing it "fire and forget". That usually means "execute this code but I'm not going to keep track of whether it completes successfully or not". For something critical, like backing up a database, you most likely don't want true fire and forget. You want the work to happen asynchronously. – mason Oct 12 '18 at 18:50
  • @mason, database backup is example. Better is sending email and sms. – night programmer Oct 12 '18 at 18:55
  • 1
    Still - what if your app suddenly started failing to send email or SMS, and the only way you found out is your customers started complaining? Those shouldn't be fire and forget either. If you're writing code, you want that code to run successfully. If it doesn't, you want to know about it so you can fix it. – mason Oct 12 '18 at 19:10

1 Answers1

4

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!

Chris.ZA
  • 1,218
  • 1
  • 15
  • 30