窥视具有无限超时的MSMQ消息

时间:2015-03-21 15:19:58

标签: c# msmq timespan peekmessage

我正在编写一个从Microsoft Message Queue(MSMQ)查看消息的应用程序。我希望我的应用程序依次查看MSMQ消息(从第一条消息到最后一条消息)。在完全查看最后一条消息后,主线程将被阻塞,直到MSMQ有新消息到达为止 我已经使用 MessageQueue.Peek(TimeSpan,Cursor,PeekAction)方法 TimeSpan = MessageQueue.InfiniteTimeout 并出现问题:MessageQueue.InfiniteTimeout值近似49天但我希望我的应用程序会等待很长时间(大约1000天)的新消息,我已经切换了TimeSpan = TimeSpan.MaxValue但没有成功。你能给我一些解决方案或建议吗?谢谢!
我的代码是这样的:



while (true) {
  if (isTheFirst) {
    try {
      ret = mq.Peek(MessageQueue.InfiniteTimeout, cursor, PeekAction.Current);
      Console.WriteLine(ret.Id);
      isTheFirst = false;
    } catch (MessageQueueException e) {
      // what can we do?
    }
  } else {
    try {
      // because MessageQueue.InfiniteTimeout value approximate 49 days, so if 
      // during 49 days, Message Queue didn't receive any message, my app will 
      // thrown exception but i want my app to continue wait for new message arrive
      ret = mq.Peek(MessageQueue.InfiniteTimeout, cursor, PeekAction.Next);
      Console.WriteLine(ret.Id);
    } catch (MessageQueueException ex) {
      // what can we do?
    }
  }
  Thread.Sleep(1000);
}




1 个答案:

答案 0 :(得分:1)

您可以尝试捕获特定错误,记录它并且循环将继续查看下一条消息。

while (true) {
  if (isTheFirst) {
    //... omitted for brievety
  } else {
    try {
      ret = mq.Peek(MessageQueue.InfiniteTimeout, cursor, PeekAction.Next);
      Console.WriteLine(ret.Id);
    } catch (MessageQueueException e) {
      if(e.MessageQueueErrorCode == MessageQueueErrorCode.IOTimeout)
      {
          Console.WriteLine("Log here that Timeout has occured");
          continue; // will skip Thread.Sleep(1000); and whatever code you put after
      }
      else
      {
         Console.WriteLine("Log exception and rethrow");
         throw;
      }
    }
  }
  Thread.Sleep(1000);
}

我不知道你具体的用例,但是等待这么长时间在队列上发送消息是不常见的。