简体   繁体   中英

Peek MSMQ message with unlimited timeout

I am writing an application that peeks message from Microsoft Message Queue (MSMQ). I want my application peeks MSMQ messages in turn(from the first message to the last message ). After peeks the last message completly, the main thread will be blocked until MSMQ have a new message arrive.
I've already used MessageQueue.Peek(TimeSpan, Cursor, PeekAction) Method with TimeSpan=MessageQueue.InfiniteTimeout and have a problem: MessageQueue.InfiniteTimeout value approximates 49 days but I want my app will wait for new message with a very very long time (about 1000 days), I've already switched TimeSpan = TimeSpan.MaxValue but have no success. Could you give me some solutions or advices? thanks!
My code like this:

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

You can try to catch the specific error, log it and the loop will continue to Peek the next message.

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

I don't know you specific use case but waiting so long time for a message on the queue is not usual.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM