1.先定義一個事件介面 2.定義一個事件處理介面 3.定義一個發佈介面 4.定義一個訂閱介面 5.創建一個類用來存事件 6.實現發佈類 7.實現訂閱類 9.測試用例 10.測試結果 ...
1.先定義一個事件介面
public interface IEvent { }
2.定義一個事件處理介面
public interface IEventHandler : IEvent { Task Handle(IEvent e); }
3.定義一個發佈介面
public interface IEventPublisher { Task Publish<TEvent>(TEvent e) where TEvent : IEvent; }
4.定義一個訂閱介面
public interface IEventSubscriber { Task Subscribe<TEvent, EH>() where TEvent : IEvent where EH : class, IEventHandler, new(); }
5.創建一個類用來存事件
public static class MemoryMq { public static ConcurrentDictionary<string, IEvent> eventQueueDict { get; set; } }
6.實現發佈類
public class InMemoryEventPublisher : IEventPublisher { public Task Publish<TEvent>(TEvent @event) where TEvent : IEvent { if (@event == null) return Task.CompletedTask; if (MemoryMq.eventQueueDict == null) { MemoryMq.eventQueueDict = new ConcurrentDictionary<string, IEvent>(); } MemoryMq.eventQueueDict.GetOrAdd(Guid.NewGuid().ToString(),@event); return Task.CompletedTask; } }
7.實現訂閱類
public class InMemoryEventSubscriber: IEventSubscriber { private readonly ConcurrentDictionary<string, Task> taskDict = new ConcurrentDictionary<string, Task>(); public Task Subscribe<TEvent, EH>() where TEvent : IEvent where EH : class, IEventHandler, new() { EH state = new EH(); Task.Run(() => { while (true) { if (MemoryMq.eventQueueDict != null) { foreach (var a in MemoryMq.eventQueueDict) { state.Handle(a.Value as IEvent); IEvent o; MemoryMq.eventQueueDict.TryRemove(a.Key ,out o); } } } }); return Task.CompletedTask; } }
9.測試用例
namespace MemoryMqTest { public class EventHandler : IEventHandler { public Task Handle(IEvent e, MessagingHelper h) { switch (e) { case Order value: Console.WriteLine(value.name); break; } return Task.CompletedTask; } } public class Order : IEvent { public string name { get; set; } } class Program { static void Main(string[] args) { var servicecollection = new ServiceCollection(); servicecollection.AddSingleton<IEventPublisher, InMemoryEventPublisher>(); servicecollection.AddSingleton<IEventSubscriber, InMemoryEventSubscriber>(); var provider = servicecollection.BuildServiceProvider(); var eventPub = provider.GetService<IEventPublisher>(); var _eventSub = provider.GetService<IEventSubscriber>(); _eventSub.Subscribe<Order, EventHandler>(); var order = new Order(); order.name = "test"; eventPub.Publish(order); Console.WriteLine("Hello World!"); Console.ReadKey(); } } }
10.測試結果