Mediatr: When using the publish mode, does not need to wait for the end of the execution of each notification Handler

Created on 14 Mar 2019  路  1Comment  路  Source: jbogard/MediatR

public class TestNotify : INotification
{
}

public class TestNotify : INotification
{
}
public class NotifyHandlerA : INotificationHandler<TestNotify>
{
public async Task Handle(TestNotify notification, CancellationToken cancellationToken)
{
    await Task.Delay(2000);
}
}
public class NotifyHandlerB : INotificationHandler<TestNotify>
{
public async Task Handle(TestNotify notification, CancellationToken cancellationToken)
{
   await Task.Delay(2000);
}
}
public class NotifyHandlerC : INotificationHandler<TestNotify>
{
public async Task Handle(TestNotify notification, CancellationToken cancellationToken)
{
   await Task.Delay(2000);
}
}`

in valuescontroller:
[HttpGet("TestNotify")]
public async Task<IActionResult> TestNotify()
{
TestNotify testNotify = new TestNotify();
await _mediator.Publish(testNotify);
return Ok("ok");
}

The execution time is about 6 seconds.

Most helpful comment

The default strategy for Publish loops through the notification handlers and awaits each one. You can change the publish strategy if you have different requirements.

From the github wiki (https://github.com/jbogard/MediatR/wiki)
"Publish strategies
The default implementation of Publish, loops through the notification handlers and awaits each one. This makes sure each handler is run after one another, while each call to 'Handle' is run asynchronously.

Depending on your use-case for publishing notifications, you might need a different strategy for handling the notifications. Maybe you want to publish all notifications in parallel, or wrap each notification handler with your own exception handling logic.

A few example implementations can be found in MediatR.Examples.PublishStrategies. This shows four different strategies documented on the PublishStrategy enum."

>All comments

The default strategy for Publish loops through the notification handlers and awaits each one. You can change the publish strategy if you have different requirements.

From the github wiki (https://github.com/jbogard/MediatR/wiki)
"Publish strategies
The default implementation of Publish, loops through the notification handlers and awaits each one. This makes sure each handler is run after one another, while each call to 'Handle' is run asynchronously.

Depending on your use-case for publishing notifications, you might need a different strategy for handling the notifications. Maybe you want to publish all notifications in parallel, or wrap each notification handler with your own exception handling logic.

A few example implementations can be found in MediatR.Examples.PublishStrategies. This shows four different strategies documented on the PublishStrategy enum."

Was this page helpful?
0 / 5 - 0 ratings