.net msmq消息队列实例详解 本文为大家分享了.net msmq消息队列实例代码,供大家参考,具体内容如下 1.msmq消息队列windows环境安装 控制面板----》程序和功能----》启用或关闭Windows程序----》Microsoft Message Queue(MSMQ)服务器 选中如图所示功能点击“确认”进行安装,安装好后可在 “计算机管理”中进行查看 2.创建消息队列实体对象 /// /// 消息实体 /// [Serializable] public class MsmqData { public int Id { get; set; } public string Name { get; set; } } 实体对象必须可序列化,即需添加[Serializable] 3.创建消息队列管理对象 /// /// 消息队列管理对象 /// public class MSMQManager { /// /// 消息队列地址 /// public string _path; /// /// 消息队列对象 /// public MessageQueue _msmq; /// /// 构造函数并初始化消息队列对象 /// /// public MSMQManager(string path = null) { if (string.IsNullOrEmpty(path)) { _path = ConfigurationManager.AppSettings["MsmqPath"].ToString(); } else { _path = path; } if (MessageQueue.Exists(_path)) { _msmq = new MessageQueue(_path); } else { _msmq = MessageQueue.Create(_path); } } /// /// 发送消息队列 /// /// public void Send(object body) { _msmq.Send(new Message(body, new XmlMessageFormatter(new Type[] { typeof(MsmqData) }))); } /// /// 接受队列中第一个消息后删除 /// /// public object ReceiveMessage() { var msg = _msmq.Receive(); if (msg != null) { //msg.Formatter = new BinaryMessageFormatter(); msg.Formatter = new XmlMessageFormatter(new Type[] { typeof(MsmqData) }); var body = (MsmqData)msg.Body; Console.WriteLine("消息内容:{0},{1}", body.Id, body.Name); return msg.Body; } return null; } /// /// 遍历消息队列中的消息并删除 /// public void WriteAllMessage() { var enumerator = _msmq.GetMessageEnumerator2(); while (enumerator.MoveNext()) { Message msg = (Message)(enumerator.Current); //msg.Formatter = new BinaryMessageFormatter(); msg.Formatter = new XmlMessageFormatter(new Type[] { typeof(MsmqData) }); var body = (MsmqData)msg.Body; Console.WriteLine("消息内容:{0},{1}", body.Id, body.Name); //根据消息ID查询并删除消息队列 _msmq.ReceiveById(msg.Id); } } } 此例中使用XML格式(XmlMessageFormtter)对消息进行格式化 4.主程序添加调用消息队列 static void Main(string[] args) { var msmqManager = new MSMQManager(); for (int i = 1; i <= 10; i++) { MsmqData data = new MsmqData() { Id = i, Name = string.Format("Name{0}", i) }; //发送消息 msmqManager.Send(data); } var msg = msmqManager.ReceiveMessage(); msmqManager.WriteAllMessage(); Console.ReadLine(); } 添加消息队列地址配置,本例使用私有队列 5.运行程序查看结果 可以在发送完消息后打上断点查看消息队列消息正文 最后运行结果 6.常见消息队列类型路径的语法 队列类型 路径中使用的语法 公共队列 MachineName\QueueName 专用队列 MachineName\Private$\QueueName 日志队列 MachineName\QueueName\Journal$ 以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持中文源码网。