Mediator
Mediator copied to clipboard
Run NotificationHandlers in parallel
One of the philosophy of notification is to notify different handlers at the same time (hopefully). currently what we do is :
for (int i = 0; i < handlers.Length; i++)
{
try
{
await handlers[i].Handle(notification, cancellationToken).ConfigureAwait(false);
}
catch (global::System.Exception ex)
{
exceptions ??= new global::System.Collections.Generic.List<global::System.Exception>();
exceptions.Add(ex);
}
}
MediatR 12 has implemented an option to define if Notifications handlers should run parallel or not. here is a link to a video demonstrate it : https://www.youtube.com/watch?v=hNxVjNO6RX4 Mediator library should add an option for these execution strategies.
imagine these two notification handlers :
public sealed class GenericNotificationHandler<TNotification> : INotificationHandler<TNotification>
where TNotification : INotification
{
public async ValueTask Handle(TNotification notification, CancellationToken cancellationToken)
{
// very long operation
await Task.Delay(10000, cancellationToken);
}
}
public sealed class GenericNotificationHandler2<TNotification> : INotificationHandler<TNotification>
where TNotification : INotification
{
public async ValueTask Handle(TNotification notification, CancellationToken cancellationToken)
{
await Task.Delay(2000, cancellationToken);
}
}
with current implementation the handling time for all the handlers would be about ~ 12000 ms but with the new implementation it would be about ~ 10000 ms