2


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 written a bit of code, but have an exception that explained like below:

Message ret = null;
Cursor cursor = mq.CreateCursor();
bool isTheFirst = true;
while (true) {
  if (isTheFirst) {
    ret = mq.Peek(new TimeSpan(Timeout.Infinite), cursor, PeekAction.Current);
    Console.WriteLine(ret.Id);
    isTheFirst = false;
  } else {
    // after my app peeks the last message completly, the peek method
   //throw an exception: "Timeout is expired!"
    ret = mq.Peek(new TimeSpan(Timeout.Infinite), cursor, PeekAction.Next);

    Console.WriteLine(ret.Id);
  }
  Thread.Sleep(1000);

}


Could anyone help me to solve this problem. Thank you!

Soner Gönül
  • 97,193
  • 102
  • 206
  • 364
GIANGPZO
  • 380
  • 2
  • 3
  • 21

1 Answers1

4

You should use MessageQueue.InfiniteTimeout instead of Timeout.infinite. Try change it to this value

ret = mq.Peek(MessageQueue.InfiniteTimeout, cursor, PeekAction.Current);

The values are not the same

var timeout = MessageQueue.InfiniteTimeout; // {49.17:02:17.2950000}
var timeout2 = new TimeSpan(Timeout.Infinite); // {-00:00:00.0000001}

So the queue Peek behaves differently

Tomasz Jaskuλa
  • 15,723
  • 5
  • 46
  • 73
  • your answer is very good, by the way, I have a small question: according to what you said, MessageQueue.InfiniteTimeout value is {49.17:02:17.2950000} that mean if message queue doesn't receive any message during about 49 day, my app will throw exception. Because I want my app will wait with infinite timeout (unlimited time), so 49 day is not enough. I've already used try catch to catch exception and then try to reset the timeout but still unsuccessfully. – GIANGPZO Mar 20 '15 at 03:06
  • I think the value of 49 days is just a value they've agreed upon for infinite timeout which is quite large in fact for waiting for a next message and blocking a thread. You can still pas a bigger timestamp if you want but I don't know your use case to tell if this is reasonable or not. – Tomasz Jaskuλa Mar 20 '15 at 12:57
  • You've already written: "**You can still pas a bigger timespan if you want but ...**" but my problem is: I can't pass a timespan that bigger than MessageQueue.InfiniteTimeout value. If possible, please advise me what to do. thanks! – GIANGPZO Mar 23 '15 at 04:00
  • Unfortunatelly this is an internal implementation of MSMQ. Is saw your other question so will try to address it there http://stackoverflow.com/questions/29184382/peek-msmq-message-with-unlimited-timeout – Tomasz Jaskuλa Mar 23 '15 at 08:35