首先安装消息队列MSMQ,在“计算机管理-服务和应用程序-消息队列-专用队列”中新建列队名称Demo:
static void SendAndReceiveMsg() { MessageQueue mq =new MessageQueue(); mq.Path = @".Private$Demo"; //构造消息 Message msg =new Message(); msg.Body ="Hello MessageQueue"; //向队列发送消息 mq.Send(msg); //读取队列中的所有消息 Message[] msgs = mq.GetAllMessages();; foreach (Message m in msgs) { m.Formatter = new System.Messaging.XmlMessageFormatter(new Type[] { typeof(string) }); Console.WriteLine(m.Body.ToString()); } //清除队列中的所有消息 mq.Purge(); }