首页 / 软件开发 / .NET编程技术 / .NET Compact Framework下的进程间通信之MSMQ开发
.NET Compact Framework下的进程间通信之MSMQ开发2011-08-29 博客园 Jake Lin上篇讲到WinCe下的MSMQ安装 ,这篇讲述一下MSMQ在.NET Compact Framework 下的开发。所谓MQ就是Message Queue,消息队列。消息队列可以作为不同应用程序之间 ,甚至不同机器之间通信的渠道。在消息队列下进行通信的内容称为消息 (Message),在C#程序下Message就是对象。MSMQ就是Microsoft公司提供的MQ服务程序。MQ服务程序负责管理消息队列, 保证消息在消息队列这一渠道下能无误的发送到对端,MQ支持离线交易,有时候 消息会缓存在MQ服务程序中,当接收方再线时候在提取消息。这一特性使得MQ可 以广泛使用在移动领域,因为移动应用的网络不能保证7×24的长连接。生成队列在CF.net下开发MQ,需要引用System.Messaging库。using System.Messaging;
public class MQService
{
private const string mMachinePrefix = @".";
private const string mPrivateQueueNamePrefix = mMachinePrefix + @"Private$";
private const string mServiceQueuePath = mPrivateQueueNamePrefix + "MQServiceQueue$";
private MessageQueue mServiceQueue;
private void InitServiceQueue()
{
// create the message queue
try
{
// check to make sure the message queue does not exist already
if (!MessageQueue.Exists (mServiceQueuePath))
{
// create the new message queue and make it transactional
mServiceQueue = MessageQueue.Create(mServiceQueuePath);
mServiceQueue.Close();
}
else
{
mServiceQueue = new MessageQueue(mServiceQueuePath);
}
Type[] types = new Type[1];
types[0] = typeof(string);
mServiceQueue.Formatter = new XmlMessageFormatter(types);
mServiceQueue.ReceiveCompleted += new ReceiveCompletedEventHandler(MessageListenerEventHandler);
// Begin the asynchronous receive operation.
mServiceQueue.BeginReceive();
mServiceQueue.Close();
}
// show message if we used an invalid message queue name;
catch (MessageQueueException MQException)
{
Console.WriteLine (MQException.Message);
}
return;
}
}
using System.Messaging;
public class MQService
{
private const string mMachinePrefix = @".";
private const string mPrivateQueueNamePrefix = mMachinePrefix + @"Private$";
private const string mServiceQueuePath = mPrivateQueueNamePrefix + "MQServiceQueue$";
private MessageQueue mServiceQueue;
private void InitServiceQueue()
{
// create the message queue
try
{
// check to make sure the message queue does not exist already
if (!MessageQueue.Exists (mServiceQueuePath))
{
// create the new message queue and make it transactional
mServiceQueue = MessageQueue.Create(mServiceQueuePath);
mServiceQueue.Close();
}
else
{
mServiceQueue = new MessageQueue(mServiceQueuePath);
}
Type[] types = new Type[1];
types[0] = typeof(string);
mServiceQueue.Formatter = new XmlMessageFormatter(types);
mServiceQueue.ReceiveCompleted += new ReceiveCompletedEventHandler(MessageListenerEventHandler);
// Begin the asynchronous receive operation.
mServiceQueue.BeginReceive();
mServiceQueue.Close();
}
// show message if we used an invalid message queue name;
catch (MessageQueueException MQException)
{
Console.WriteLine (MQException.Message);
}
return;
}
}