internal RedisQueueService() { m_contexts = new List <MqSubscribeContext>(); m_thrWorkMQ = new Thread(() => { while (true) { if (m_exitWorkMQ) { Thread.Sleep(1); } else { bool untreated = false; // 未处理过 for (int i = 0; i < m_contexts.Count; i++) { MqSubscribeContext context = m_contexts[i]; m_workReadMQ.Chanels = context.MqChanels; string message = m_workReadMQ.Dequeue(); if (message != null) { untreated = true; try { Action <string> d = context.EventHandler; d(message); } #pragma warning disable CS0168 // 声明了变量“ex”,但从未使用过 catch (Exception ex) #pragma warning restore CS0168 // 声明了变量“ex”,但从未使用过 { continue; } } } if (!untreated) { Thread.Sleep(1); } } } }) { IsBackground = true, Priority = ThreadPriority.Lowest }; m_thrWorkMQ.Start(); m_workReadMQ = new RedisQueue(typeof(RedisQueueService).Name); m_workWriteMQ = new RedisQueue(typeof(RedisQueueService).Name); }
/// <summary> /// 订阅消息队列 /// </summary> /// <param name="chanels">消息队列</param> public void Subscribe <T>(string chanels, Action <T> handler) where T : class, new() { if (handler == null) { throw new ArgumentNullException("handler"); } if (string.IsNullOrEmpty(chanels)) { throw new ArgumentException("chanels"); } lock (m_contexts) { if (m_contexts.FirstOrDefault((i) => i.MqChanels == chanels) != null) { throw new ArgumentException("repeat"); } MqSubscribeContext context = new MqSubscribeContext { EventHandler = (message) => { T value = null; if (typeof(string) != typeof(T)) { if (!string.IsNullOrEmpty(message)) { value = StringFormatter.Deserialize <T>(message); } } else { object obj = message; value = (T)obj; } handler(value); }, EventType = typeof(T), MqChanels = chanels }; m_contexts.Add(context); } }