Message Queue Windows Service

霸气de小男生 提交于 2019-12-05 09:35:45

问题


I wish to write a windows service in .Net 2.0 that listens to and processes a Message Queue (MSMQ).

Rather than reinvent the wheel, can someone post an example of the best way to do it? It only has to process things one at a time, never in parallel (eg. Threads).

Essentially I want it to poll the queue, if there's anything there, process it, take it off the queue and repeat. I want to do this in a system-efficient way as well.

Thanks for any suggestions!


回答1:


There are a few different ways you can do the above. I would recommend setting up an event on the message queue so that you are notified when a message is available rather than polling for it.

Simple example of using message queues is http://www.codeproject.com/KB/cs/mgpmyqueue.aspx and the MSDN documentation for attaching events etc can be found at http://msdn.microsoft.com/en-us/library/system.messaging.messagequeue_events.aspx

Microsoft example from here:

           ....
           // Create an instance of MessageQueue. Set its formatter.
           MessageQueue myQueue = new MessageQueue(".\\myQueue");
            myQueue.Formatter = new XmlMessageFormatter(new Type[]
                {typeof(String)});

            // Add an event handler for the ReceiveCompleted event.
            myQueue.ReceiveCompleted += new 
                ReceiveCompletedEventHandler(MyReceiveCompleted);

            // Begin the asynchronous receive operation.
            myQueue.BeginReceive();
            ....


        private static void MyReceiveCompleted(Object source, 
            ReceiveCompletedEventArgs asyncResult)
        {
            // Connect to the queue.
            MessageQueue mq = (MessageQueue)source;

            // End the asynchronous Receive operation.
            Message m = mq.EndReceive(asyncResult.AsyncResult);

            // Display message information on the screen.
            Console.WriteLine("Message: " + (string)m.Body);

            // Restart the asynchronous Receive operation.
            mq.BeginReceive();

            return; 
        }



回答2:


Check out the WCF examples at http://msdn.microsoft.com/en-us/library/ms751514.aspx.

EDIT: Note that my answer was given before the edit to specify using .Net 2.0. I still think WCF is the way to go, but it would require .NET 3.0, at least.



来源:https://stackoverflow.com/questions/576303/message-queue-windows-service

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!