代码之家  ›  专栏  ›  技术社区  ›  Chris KL

消息队列Windows服务

  •  1
  • Chris KL  · 技术社区  · 16 年前

    我希望在.NET 2.0中编写一个Windows服务,用于侦听和处理消息队列(msmq)。

    不是重新发明轮子,有人能举一个最好的例子吗?它只需要一次处理一个事务,而不需要并行处理(例如线程)。

    本质上,我希望它轮询队列,如果其中有任何内容,处理它,将其从队列中取出并重复。我也希望以一种系统高效的方式来实现这一点。

    谢谢你的建议!

    2 回复  |  直到 16 年前
        1
  •  4
  •   Rosstified    16 年前

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

    使用消息队列的简单示例是 http://www.codeproject.com/KB/cs/mgpmyqueue.aspx 有关附加事件等的msdn文档,请访问 http://msdn.microsoft.com/en-us/library/system.messaging.messagequeue_events.aspx

    Microsoft示例来自 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
  •  4
  •   tvanfosson    16 年前

    查看wcf示例 http://msdn.microsoft.com/en-us/library/ms751514.aspx .

    编辑: 请注意,我的答案是在使用.NET 2.0指定的编辑之前给出的。我仍然认为wcf是一种方式,但它至少需要.NET 3.0。