消息队列循环

时间:2011-03-17 18:27:51

标签: c# msmq

我在c#中有一个控制台应用程序,我正在尝试从消息队列接收消息,直到消息队列为空。等等,

MessageQueue queue = new MessageQueue();
While(queue.notempty)
{
    queue.receive(...)
}

我该怎么做?

感谢。

3 个答案:

答案 0 :(得分:5)

无法检查队列是否为空。你必须这样收到它:

private Message Receive(MessageQueue queue)
{
   try 
   {
      return queue.Receive(TimeSpan.Zero);
   }
   catch (MessageQueueException mqe)
   {
      if (mqe.MessageQueueErrorCode == MessageQueueErrorCode.IOTimeout)
         return null;
      throw;
   }
}

然后你可以做

MessageQueue queue = new MessageQueue();
Message msg;
while( (msg = Receive(queue)) != null)
{
    //process
}

答案 1 :(得分:0)

如果你在C#中这样做,Queue<T>类应该可以工作:

Queue<Message> queue = GetMessageQueue();

while(queue.Count > 0)
{
     Message message = queue.Dequeue();
     // process message
}

如果您计划从多个线程填充队列,可以考虑使用ConcurrentQueue<T>(或BlockingCollection<T>)。


如果您使用MS {MessageQueue类,则可以始终使用:

MessageQueue queue = ...

TimeSpan timeout = TimeSpan.FromMilliseconds(100); // Small timeout - can be very small

Message message = queue.Receive(timeout);
while (message != null)
{
      // Process message...


      message = queue.Receive(timeout);
}

答案 2 :(得分:0)

 public class PersonDetails
 {
   public string FirstName { get; set; }
   public string LastName { get; set; }
   public DateTime DateTime { get; set; }
 }

     const string queueName = @".\private$\PersonQueue";

     public void GetMessageFromQueue(string queueName)
     {
      MessageQueue perosnMessageQueue = new MessageQueue(queueName);
     try
     {
     XmlMessageFormatter xmlMessageFormatter = new XmlMessageFormatter(new Type[] { 
                               (typeof(PersonDetails)) });
      perosnMessageQueue.Formatter = xmlMessageFormatter;
      perosnMessageQueue.Refresh();
      for (int i = perosnMessageQueue.GetAllMessages().Count(); i !=0; i--)
      {
      var personDetailsFromQueue =
                         (PersonDetails)perosnMessageQueue.Receive
                         (MessageQueueTransactionType.Automatic).Body;

        Console.WriteLine("FistName : {0} \n LastName : {1} \n Date Time : 
         {2}",personDetailsFromQueue.FirstName, 
              personDetailsFromQueue.LastName, 
              personDetailsFromQueue.DateTime);`  
       }