Peek MSMQ message with unlimited timeout

ε祈祈猫儿з 提交于 2019-12-11 09:09:53

问题


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

回答1:


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.



来源:https://stackoverflow.com/questions/29184382/peek-msmq-message-with-unlimited-timeout

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!