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 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?
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.