在MultiThreading Service中听什么更好的方法?

我对MSMQ和.NET中的线程都相对较新。 我必须创建一个服务,通过TCP和SNMP,几个网络设备以及所有这些东西在专用线程中运行,以不同的线程监听,但是这里也需要从另一个应用程序监听MSMQ队列。 我正在分析另一个类似的项目,并使用下一个逻辑:

private void MSMQRetrievalProc() { try { Message mes; WaitHandle[] handles = new WaitHandle[1] { exitEvent }; while (!exitEvent.WaitOne(0, false)) { try { mes = MyQueue.Receive(new TimeSpan(0, 0, 1)); HandleMessage(mes); } catch (MessageQueueException) { } } } catch (Exception Ex) { //Handle Ex } } MSMQRetrievalThread = new Thread(MSMQRetrievalProc); MSMQRetrievalThread.Start(); 

但是在另一个服务(消息调度程序)中,我使用基于MSDN的异步消息读取示例 :

 public RootClass() //constructor of Main Class { MyQ = CreateQ(@".\Private$\MyQ"); //Get or create MSMQ Queue // Add an event handler for the ReceiveCompleted event. MyQ.ReceiveCompleted += new ReceiveCompletedEventHandler(MsgReceiveCompleted); // Begin the asynchronous receive operation. MyQ.BeginReceive(); } private void MsgReceiveCompleted(Object source, ReceiveCompletedEventArgs asyncResult) { try { // Connect to the queue. MessageQueue mq = (MessageQueue)source; // End the asynchronous Receive operation. Message m = mq.EndReceive(asyncResult.AsyncResult); // Process received message // Restart the asynchronous Receive operation. mq.BeginReceive(); } catch (MessageQueueException Ex) { // Handle sources of MessageQueueException. } return; } 

异步处理是否假设每个消息都将在主线程以外的地方处理? 可以并且需要将这个(第二个)方法放在单独的线程中吗?

请建议更好的方法或一些简单的选择。

到达队列的邮件没有一些规则定义的行为。 可能是很长一段时间没有任何消息将会到达,或者在一秒钟内我会收到许多(最多10个甚至更多)消息。 根据某些消息中定义的操作,它将需要删除/更改一些具有运行线程的对象。

我强烈建议使用WCF进行MSMQ。

http://msdn.microsoft.com/en-us/library/ms789048.aspx

这允许您使用WCF线程模型异步处理传入调用,该模型允许限制,上限,重试等…