publicclassHeadedEvent:Event { publicstring Name { get; set; } }
publicclassGuoJiZhangMotherEventHandler : IEventHandler<HeadedEvent> { publicvoidHandle(HeadedEvent e) { Console.WriteLine(e.Name+", Are you kidding me?"); } }
publicclassPiMingEventHandler:IEventHandler<HeadedEvent> { publicvoidHandle(HeadedEvent e) { Console.WriteLine(e.Name+", Guo Ji Zhang is your last wife?"); } }
我们可以看到正真的事件协调者是EventBus, 之前的代码如下是同步的。
1 2 3 4 5 6 7 8 9 10 11
publicclassEventBus { publicstaticvoidPublish<T>(T concreteEvent) where T: Event { var handlers = _container.ResolveAll<IEventHandler<T>>(); foreach (var handle in handlers) { handle.Handle(concreteEvent); } } }
为了提高性能,我们可以先来第一步改进
1 2 3 4 5 6 7
publicvoidPublish<T>(T @event) where T : Event { var handlers = _eventHandlerFactory.GetHandlers<T>();