C#进程间通信:[1]微软消息服务(MSMQ) 听语音
- |
- 浏览:1564
- |
- 更新:2013-09-13 13:39
一键约师傅
百度师傅高质屏和好师傅,拯救你的碎屏机
百度经验:jingyan.baidu.com
本文介绍在C#中如何使用微软消息服务(MSMQ)经行进程间的通信。
百度经验:jingyan.baidu.com
工具/原料
- Visual Studio 2013(VS2012、VS2010、VS2008等其他开发环境均可)。
- 微软消息服务(MSMQ,具体安装方法见参考资料)。
百度经验:jingyan.baidu.com
方法/步骤
-
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<string >(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控件中,如下图。
步骤阅读
END
百度经验:jingyan.baidu.com
注意事项
- 需要引用System.Messaging文件,并且在代码中好要Using一下。
- 使用System.Messaging时需要安装MSMQ消息服务。
- 在不是创建控件的线程中无法调用控件的方法,使用Control.Invoke即可。
C#进程间通信 (共3篇)