问题
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