2012-09-17 49 views
4

我在.NET中对MSMQ和线程都比较新。我必须创建一个服务,通过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 Example异步消息的阅读:

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条甚至更多)消息。根据某些消息中定义的动作,它需要删除/更改某些正在运行线程的对象。

回答

1

我强烈建议使用WCF for MSMQ。

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

这可以让你异步处理使用WCF线程模型允许节流,封盖,重试,等来电...

+0

谢谢@汤姆·安德森,但我仅限于.NET2.0和消息主题之一是Delphi应用程序 - 看起来这里不可能将WCF应用于MSMQ – ALZ

相关问题