C#进程间通信:[1]微软消息服务(MSMQ)
听语音
- |
- 浏览:1564
- |
- 更新:2013-09-13 13:39
本文介绍在C#中如何使用微软消息服务(MSMQ)经行进程间的通信。
方法/步骤
-
启动VS,新建WinForm项目,命名为MSMQ,用来发送消息,如下:
-
以新建窗口的方式启动VS,新建WinForm项目,命名为MSMQ2,用来接收消息,如下:
-
以上两个项目中均添加,System.Messaging引用,如下图:
-
MSMQ项目窗口设计,如下图:
-
MSMQ2项目窗口设计,如下图:
-
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 );
}
}
}
-
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<string >(ShowMsg),str);
//继续下一条消息
mq.BeginReceive();
}
private void ShowMsg(string msg) {
this.textBox1 .Text =this.textBox1.Text+ msg+Environment .NewLine ;
return;
}
}
}
-
调试运行:分别启动MSMQ和MSMQ2,在MSMQ中的TextBox中输入字符串,然后点击发送,MSMQ2将会收到消息,并显示在TextBox控件中,如下图。
END