注意:mediatR发布-订阅,订阅方是多个的时候是串行的,一个执行完才执行下一个
// 发送部分代码Console.WriteLine($"{DateTime.Now}-发送开始-");mediator.Publish<TestEvent>(new TestEvent("nancy"));Console.WriteLine($"{DateTime.Now}-发送完毕-");
订阅方-串行执行代码如下:
//订阅方1的代码
public class TestEventHandler1 : INotificationHandler<TestEvent>
{public Task Handle(TestEvent notification, CancellationToken cancellationToken){return Task.Run(async () =>{Console.WriteLine($"{DateTime.Now}-TestEventHandler1 我收到了{notification.UserName}");await Task.Delay(5000);Console.WriteLine($"{DateTime.Now}-TestEventHandler1 -结束");});//return Task.CompletedTask;}
}
//订阅方2的代码public class TestEventHandler2 : INotificationHandler<TestEvent>{public Task Handle(TestEvent notification, CancellationToken cancellationToken){return Task.Run(async () =>{Console.WriteLine($"{DateTime.Now}-TestEventHandler2 我收到了{notification.UserName}");await Task.Delay(5000);Console.WriteLine($"{DateTime.Now}-TestEventHandler2 -结束");});//return Task.CompletedTask;}}//订阅方3的代码public class TestEventHandler3 : INotificationHandler<TestEvent>{public Task Handle(TestEvent notification, CancellationToken cancellationToken){return Task.Run(async () =>{Console.WriteLine($"{DateTime.Now}-TestEventHandler3 我收到了{notification.UserName}");await Task.Delay(5000);Console.WriteLine($"{DateTime.Now}-TestEventHandler3 -结束");});//return Task.CompletedTask;}}
运行结果:
通过以下方式改为并行:
需在task.run之后 return Task.CompletedTask;直接ruturn task.run 可能框架会await,会等待task.run 内的代码执行完毕后才返回,失去了异步的目的
订阅方-并行执行代码如下:
public class TestEventHandler1 : INotificationHandler<TestEvent>{public Task Handle(TestEvent notification, CancellationToken cancellationToken){Task.Run(async () =>{Console.WriteLine($"{DateTime.Now}-TestEventHandler1 我收到了{notification.UserName}");await Task.Delay(5000);Console.WriteLine($"{DateTime.Now}-TestEventHandler1 -结束");});return Task.CompletedTask;}}public class TestEventHandler2 : INotificationHandler<TestEvent>{public Task Handle(TestEvent notification, CancellationToken cancellationToken){Task.Run(async () =>{Console.WriteLine($"{DateTime.Now}-TestEventHandler2 我收到了{notification.UserName}");await Task.Delay(5000);Console.WriteLine($"{DateTime.Now}-TestEventHandler2 -结束");});return Task.CompletedTask;}}public class TestEventHandler3 : INotificationHandler<TestEvent>
{public Task Handle(TestEvent notification, CancellationToken cancellationToken){Task.Run(async () =>{Console.WriteLine($"{DateTime.Now}-TestEventHandler3 我收到了{notification.UserName}");await Task.Delay(5000);Console.WriteLine($"{DateTime.Now}-TestEventHandler3 -结束");});return Task.CompletedTask;}
运行结果: