1

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

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

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

感谢您的任何建议!

4

2 回答 2

4

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

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

于 2009-02-23T01:47:34.127 回答
4

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

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

此处的 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; 
        }
于 2009-02-23T02:15:48.490 回答