消息队列Windows服务

时间:2009-02-23 01:42:56

标签: .net msmq

我希望在.Net 2.0中编写一个监听和处理消息队列(MSMQ)的Windows服务。

不是重新发明轮子,有人可以发布一个最佳方法的例子吗?它只需要一次处理一个事物,而不是并行处理(例如,线程)。

基本上我希望它轮询队列,如果有任何东西,处理它,把它从队列中取出并重复。我想以系统效率的方式做到这一点。

感谢您的任何建议!

2 个答案:

答案 0 :(得分:4)

查看http://msdn.microsoft.com/en-us/library/ms751514.aspx处的WCF示例。

编辑:请注意,我的答案是在编辑之前给出的,以指定使用.Net 2.0。我仍然认为WCF是可行的方法,但它至少需要.NET 3.0。

答案 1 :(得分:4)

您可以通过以下几种方式完成上述操作。我建议在消息队列上设置一个事件,以便在消息可用时通知您,而不是轮询它。

使用消息队列的简单示例是http://www.codeproject.com/KB/cs/mgpmyqueue.aspx,可以在以下位置找到用于附加事件等的MSDN文档 http://msdn.microsoft.com/en-us/library/system.messaging.messagequeue_events.aspx

来自here的Microsoft示例:

           ....
           // 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; 
        }
相关问题