【问题标题】:Message Queue Windows Service消息队列 Windows 服务
【发布时间】:2009-02-23 10:15:48
【问题描述】:

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

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

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

感谢您的任何建议!

【问题讨论】:

    标签: .net msmq


    【解决方案1】:

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

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

    来自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】:

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

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

      【讨论】:

      • 我宁愿避免使用 WCF,而只坚持使用 .Net 2.0 风格的操作。
      • 为什么?忽略 WCF 的所有优点似乎是一种浪费。使用 WCF,这将非常容易。
      猜你喜欢
      • 1970-01-01
      • 2012-03-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-02-23
      • 1970-01-01
      • 2011-05-23
      • 1970-01-01
      相关资源
      最近更新 更多