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條甚至更多)消息。根據某些消息中定義的動作,它需要刪除/更改某些正在運行線程的對象。
謝謝@湯姆·安德森,但我僅限於.NET2.0和消息主題之一是Delphi應用程序 - 看起來這裏不可能將WCF應用於MSMQ – ALZ