tags:

views:

1051

answers:

2

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!

+3  A: 

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.

tvanfosson
I'd rather avoid WCF, and just stick with .Net 2.0 style operations.
Chris KL
Why? Seems like a waste to ignore all the advantages of WCF. With WCF this would be pretty easy.
tvanfosson
+3  A: 

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; 
        }
RM