using System; using System.Messaging; namespace HMI.Simple.Util { public class MSMQHelper : IDisposable { /// /// 消息队列名称 /// private string msmqName = string.Empty; /// /// 消息队列路径 /// private string msmqPath = string.Empty; /// /// 要操作的消息队列 /// private MessageQueue msgQueue = null; /// /// 构造函数 /// /// 消息队列名称 public MSMQHelper(string Name) { try { this.msmqName = Name; this.msmqPath = ".\\private$\\" + this.msmqName; if (MessageQueue.Exists(this.msmqPath)) { // 如果当前消息队列已经存在 this.msgQueue = new MessageQueue(this.msmqPath); } else { // 如果消息队列不存在,则创建消息对垒 this.msgQueue = MessageQueue.Create(this.msmqPath); } this.msgQueue.Formatter = new XmlMessageFormatter(new Type[] { typeof(string) }); } catch (Exception ex) { throw new Exception(ex.Message); } } /// /// 发送消息 /// /// 消息ID /// 要发送的字符串 public void Send(string MessageID, string MsgString) { try { this.msgQueue.Send(MsgString, MessageID); } catch (Exception ex) { throw new Exception(ex.Message); } } /// /// 接收消息队列中的消息 /// /// 超时时间(ms) /// 消息ID /// 消息内容 public void Receive(long TimeOut, out string MessageID, out string MsgString) { try { MessageID = string.Empty; MsgString = string.Empty; TimeSpan Time = new TimeSpan(TimeOut); Message MsgReceived = null; try { MsgReceived = this.msgQueue.Receive(Time); } catch { // do nothing } if (MsgReceived != null) { MessageID = MsgReceived.Label; MsgString = MsgReceived.Body.ToString(); } } catch (Exception ex) { throw new Exception("接收消息失败:" + ex.Message); } } /// /// 清除消息队列中的消息 /// public void Clear() { try { this.msgQueue.Purge(); } catch (Exception ex) { throw new Exception("清除消息队列失败:" + ex.Message); } } /// /// 关闭当前队列 /// public void Close() { this.msgQueue.Close(); } /// /// 删除当前队列 /// public void Delete() { MessageQueue.Delete(this.msmqPath); } public void Dispose() { this.Close(); } } }