直接上代码,简单直观:

//Author:FengZiLi
//Date:
using Tiexue.UI.Common;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Messaging;
using System.IO;

namespace Battlefront.MsmqStudy
{
    public class MessageQueueStudy:IDisposable
    {
        public MessageQueueStudy(string messageQueueName)
        {
            this.MessageQueuePath = messageQueueName;
        }

        public void Run()
        {
            this.EnsureMessageQueueExist();
            this.SendMessageTest();
            Console.ReadLine();
            this.ReadMessageTest();
        }

        private void EnsureMessageQueueExist()
        {
            if (MessageQueue.Exists(this.MessageQueuePath))
            {
                this.Queue = new MessageQueue(this.MessageQueuePath, QueueAccessMode.SendAndReceive);
                return;
            }
            this.Queue = MessageQueue.Create(this.MessageQueuePath);
        }

        private void ReadMessageTest()
        {
            while (true)
            {
                Message msg = this.Queue.Receive();
                using (StreamReader srd = new StreamReader(msg.BodyStream))
                {
                    Console.WriteLine(srd.ReadToEnd());
                }
            }

            foreach (Message msg2 in this.Queue.GetAllMessages())
            {
                using (StreamReader srd = new StreamReader(msg2.BodyStream))
                {
                    Console.WriteLine(srd.ReadToEnd());
                }
            }
        }

        private void SendMessageTest()
        {
            Console.WriteLine("请输入消息");
            Message msg = new Message("Content" + Console.ReadLine());
            this.Queue.Send(msg);
        }


        public string MessageQueuePath
        {
            get;
            set;
        }

        public MessageQueue Queue { get; set; }


        ~MessageQueueStudy()
        {
            this.Dispose();
        }

        private bool _Disposed;
        public void Dispose()
        {
            if (this._Disposed==false && this.Queue != null)
            {
                this.Queue.Dispose();
                GC.SuppressFinalize(this);
            }
            this._Disposed = true;
        }
    }
}