I am relatively new to both MSMQ and Threading in .NET. I need to create a service that listens on different threads through TCP and SNMP, several network devices, and all this happens in dedicated threads, but it also requires listening to the MSMQ queue from other applications. I analyze other similar projects, and the following logic is used:
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) {
But in another service (message manager) I used reading asynchronous messages based on 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; }
Asynchronous processing assumes that each message will be processed differently than the main thread? Can this (2nd) approach be placed in a separate thread?
Please suggest a better approach or some simple alternatives.
The arrival of messages in the queue does not have a specific rule. It may happen that for a long time no message arrives, or after one second I do not receive many (up to 10 or even more) messages. Based on the actions defined in a message, it will be necessary to delete / modify some objects with running threads.
source share