1

我正在编写一个从 Microsoft 消息队列 (MSMQ) 中窥视消息的应用程序。我希望我的应用程序依次查看 MSMQ 消息(从第一条消息到最后一条消息)。在完全窥视完最后一条消息后,主线程将被阻塞,直到 MSMQ 有新消息到达。
我已经使用了带有TimeSpan=MessageQueue.InfiniteTimeout的MessageQueue.Peek(TimeSpan, Cursor, PeekAction) 方法并且有一个问题: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);
}

4

1 回答 1

1

您可以尝试捕获特定错误并将其记录下来,然后循环将继续 Peek 下一条消息。

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);
}

我不知道您的具体用例,但在队列中等待这么长时间的消息并不常见。

于 2015-03-23T08:47:27.817 回答