将发送一条消息给多个消费者。这种模式被称为“发布/订阅”。
- 降低了耦合。发布者不知道订阅者的数量,订阅者的身份或订阅者订阅的消息类型的数量。
- 提高安全性。通信基础设施仅将已发布的消息传输到订阅了相应主题的应用程序。特定的应用程序可以直接交换消息,不包括消息交换中的其他应用
- 改进的可测性。主题通常会减少测试所需的消息数量。
事件的声明:
using Prism.Events; using System.Collections.Generic; using TradeStation.Modules.Trade.Models; namespace TradeStation.Modules.Trade.Event { public class BasketOrderListEvent : PubSubEvent<List<STPOrderReqBasketItem>> { } }
事件的发布
private IEventAggregator _eventAggregator; public AddBasketAlertViewModel(IEventAggregator eventAgg) { _eventAggregator = eventAgg; } private void OnConfirmAddBasketCommand(Window window) { if (ImportSuccess < 0) { System.Windows.MessageBox.Show("导入的文件格式错误,请选择正确的格式", "警告", MessageBoxButton.OK, MessageBoxImage.Information); return; } if (ImportSuccess > 0) { _eventAggregator.GetEvent<BasketOrderListEvent>().Publish(basketOrderList); } }
事件的订阅
构造函数中初始化 EventAggregator.GetEvent<BasketOrderListEvent>().Subscribe(OnBasketOrderListEventHandler); private void OnBasketOrderListEventHandler(List<STPOrderReqBasketItem> basketOrderList) { var importCount = 0; STPBasketOrderList.Clear(); lock (STPBasketOrderList) { foreach (var orderReq in basketOrderList) { var securityInfo = _marketDataService.GetSecurityInfo(orderReq.ExchangeID, orderReq.InstrumentID); if (null != securityInfo && !STPBasketOrderList.Any(x => x.ExchangeID == orderReq.ExchangeID && x.InstrumentID == orderReq.InstrumentID)) { _marketDataService.SubscribeSecQuot(new ExSecID(securityInfo.ExID, securityInfo.SecurityID)); orderReq.SecurityInfo = securityInfo; orderReq.LimitPrice = CommonUtil.GetPriceFromPriceLevel( orderReq.SecurityInfo, BashOperationInfo.OrderPriceLevel, BashOperationInfo.Direction_E); STPBasketOrderList.Add(orderReq); importCount++; } } MessageBox.Show($"共导入合法数据{importCount}条", "提示", MessageBoxButton.OK, MessageBoxImage.Information); }