简体   繁体   中英

What is better approach to listen in MultiThreading Service?

I am relatively new both to MSMQ and Threading in .NET. I have to create a service which listen in different threads, via TCP and SNMP, several network Devices and all this stuff run in dedicated threads, but here also is required to listen on MSMQ Queue from another applications. I am analyzing another similar projects and there is used next logic:

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();

But in another service (message dispatcher) I used asynchronous messages' reading 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;
}

Does asynchronous handling suppose that every message will be handled in other than main thread? Could and need this (2nd) approach be put in separate thread?

Please advice better approach or some simple alternatives.

Messages arrival in Queue doesn't have some rule-defined behavior. It may be that for long time no nay message will arrive or in one second there my arrive many (up to 10 or even more) messages. Based on actions defined in some message it will need to delete/change some objects having running threads.

I highly recommend using WCF for MSMQ.

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

This allows you to both asynchronous handle the incoming calls using the WCF threading model which allows for throttling, capping, retries, etc...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM