我已经创建了一个从 MSMQueue 读取消息的 Windows 服务,我需要并行执行(两个线程应该同时读取消息)。我怎样才能做到这一点?这是我的代码(几乎是书本):
public partial class MyNewService : ServiceBase
{
System.Messaging.MessageQueue mq;
System.Messaging.Message mes;
public MyNewService()
{
InitializeComponent();
if (MessageQueue.Exists("MyServer\\MyQueue"))
mq = new System.Messaging.MessageQueue("MyServer\\MyQueue");
mq.ReceiveCompleted += new ReceiveCompletedEventHandler(MyReceiveCompleted);
mq.BeginReceive();
}
private static void MyReceiveCompleted(Object source, ReceiveCompletedEventArgs asyncResult)
{
try
{
MessageQueue mq = (MessageQueue)source;
Message m = mq.EndReceive(asyncResult.AsyncResult);
// TODO: Process the m message here
// Restart the asynchronous receive operation.
mq.BeginReceive();
}
catch(MessageQueueException)
{
// Handle sources of MessageQueueException.
}
return;
}
}
这是我的主要功能:
static class Program
{
static void Main()
{
ServiceBase[] ServicesToRun;
ServicesToRun = new ServiceBase[]
{
new MyNewService()
};
ServiceBase.Run(ServicesToRun);
}
}