Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MediatR NotificationHandler fire and forget

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?

like image 842
night programmer Avatar asked Nov 02 '25 13:11

night programmer


1 Answers

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!

like image 93
Chris.ZA Avatar answered Nov 04 '25 04:11

Chris.ZA



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!