多语言展示
当前在线:1945今日阅读:19今日分享:20

C#进程间通信:[1]微软消息服务(MSMQ)

本文介绍在C#中如何使用微软消息服务(MSMQ)经行进程间的通信。
工具/原料
1

Visual Studio 2013(VS2012、VS2010、VS2008等其他开发环境均可)。

2

微软消息服务(MSMQ,具体安装方法见参考资料)。

方法/步骤
1

启动VS,新建WinForm项目,命名为MSMQ,用来发送消息,如下:

2

以新建窗口的方式启动VS,新建WinForm项目,命名为MSMQ2,用来接收消息,如下:

3

以上两个项目中均添加,System.Messaging引用,如下图:

4

MSMQ项目窗口设计,如下图:

5

MSMQ2项目窗口设计,如下图:

6

MSMQ代码如下:namespace MSMQ{    public partial class Form1 : Form    {        public Form1()        {            InitializeComponent();        }        MessageQueue mq;        private void Form1_Load(object sender, EventArgs e)        {            //新建消息循环队列或连接到已有的消息队列            string path = '.\\private$\\killf';            if (MessageQueue.Exists(path))            {                mq = new MessageQueue(path);            }            else            {                mq = MessageQueue.Create(path);            }            mq.Formatter = new XmlMessageFormatter(new Type[] { typeof(string) });                   }        private void button2_Click(object sender, EventArgs e)        {            mq.Send(textBox1 .Text );        }    }}

7

MSMQ2代码如下:namespace MSMQ2{    public partial class Form1 : Form    {        public Form1()        {            InitializeComponent();        }        MessageQueue mq;        private void Form1_Load(object sender, EventArgs e)        {            //新建消息循环队列或连接到已有的消息队列            string path = '.\\private$\\killf';            if (MessageQueue.Exists(path))            {                mq = new MessageQueue(path);            }            else            {                mq = MessageQueue.Create(path);            }            mq.Formatter = new XmlMessageFormatter(new Type[] { typeof(string) });            mq.ReceiveCompleted += mq_ReceiveCompleted;            mq.BeginReceive();        }        void mq_ReceiveCompleted(object sender, ReceiveCompletedEventArgs e)        {            //throw new NotImplementedException();            MessageQueue mq = (MessageQueue)sender;            System .Messaging .Message m = mq.EndReceive(e.AsyncResult);            //处理消息            string str = m.Body.ToString();            this.textBox1.Invoke(new Action(ShowMsg),str);                        //继续下一条消息            mq.BeginReceive();        }       private  void ShowMsg(string msg) {            this.textBox1 .Text =this.textBox1.Text+ msg+Environment .NewLine ;            return;        }    }}

8

调试运行:分别启动MSMQ和MSMQ2,在MSMQ中的TextBox中输入字符串,然后点击发送,MSMQ2将会收到消息,并显示在TextBox控件中,如下图。

注意事项
1

需要引用System.Messaging文件,并且在代码中好要Using一下。

2

使用System.Messaging时需要安装MSMQ消息服务。

3

在不是创建控件的线程中无法调用控件的方法,使用Control.Invoke即可。

推荐信息