我已经制作了一个从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);
}
}
答案 0 :(得分:3)
是否有理由不能在多个线程上进行处理而不是在多个线程上出列?
这是 very 基本实现 - 它使用ThreadPool
对项目进行排队,但您依靠ThreadPool
的队列来处理线程数和工作项目的数量。根据许多其他因素,这可能不适合您的情况。
另外,请注意关于SetMaxThreads
here的备注部分。
private static void MyReceiveCompleted(Object source, ReceiveCompletedEventArgs asyncResult)
{
try
{
MessageQueue mq = (MessageQueue)source;
Message m = mq.EndReceive(asyncResult.AsyncResult);
// TODO: Process each message on a separate thread
// This will immediately queue all items on the threadpool,
// so there may be more threads spawned than you really want
// Change how many items are allowed to process concurrently using ThreadPool.SetMaxThreads()
System.Threading.ThreadPool.QueueUserWorkItem(new WaitCallback(doWork), m);
// Restart the asynchronous receive operation.
mq.BeginReceive();
}
catch(MessageQueueException)
{
// Handle sources of MessageQueueException.
}
return;
}
private static void doWork(object message)
{
// TODO: Actual implementation here.
}
答案 1 :(得分:1)
我会在多个Windows服务上托管队列读取器的单线程实例。
通过这种方式,您可以通过启动其他服务来提高吞吐量,或者通过退回来减少吞吐量。这比尝试在代码中完成所有操作要简单得多。