I want to be able to read and process messages from MSMQ. Queues are transactional. I am 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 System.Messaging.MessageQueue .
I would like to use a while (!cancelled) , which means calling queue.Receive , which overloads, which takes a timeout. However, the code throws when the timeout is reached, and throwing so many exceptions may not be good. Is there a TryRecieve similar to Monitor.TryEnter ? Peek seems to be the closest, but it also fires when a timeout is reached.
If I want to get high throughput from the queue and support cancellation, what is the best way to read from the queue?
source share