MSMQ receive timeouts from .NET
I want to be able to read and process messages from MSMQ. The queues are transactional. I'm currently using this code:
while (true)
{
using (var txn = new MessageQueueTransaction())
{
txn.Begin();
try
{
var message = queue.Receive(txn);
Dispatch(message);
txn.Commit();
}
catch (MessageQueueException ex)
{
txn.Abort();
}
}
}
Where queue
is a System.Messaging.MessageQueue
.
I'd like to make开发者_如何学Python the loop use while (!cancelled)
, which would mean calling the queue.Receive
that overload that accepts a timeout. However, the code throws when the timeout is reached, and throwing so many exceptions can't be a good thing. Is there a TryRecieve
, similar to Monitor.TryEnter
? Peek seems to be the closest, but it also throws when the timeout is reached.
If I want high throughput reading from a queue and cancellation support, what's the best way to read from the queue?
Use MessageQueue.BeginPeek() instead. The event handler you write for the PeekCompleted event will run as soon as a message is available. You can call Receive() and be sure you'll get a message without a timeout. There's a good example in the MSDN Library article.
Not a direct answer, but I would use the net.msmq protocol in WCF to do my messageQ handling. Its a neat simple approach and can cater for all the scenarios you have mentioned here.
精彩评论