Yes, you are correct in assuming that exceptions are costly. This is actually a cast that is expensive rather than catching. Typically, a queue should be empty from time to time, and a normal state should not result in an exception being thrown.
Using MessageQueue.GetMessageEnumerator2, we can use a counter to determine if the queue is empty or not without loading all messages. With this approach, we will never upload more than one message.
Example:
private static bool IsQueueEmpty(MessageQueue queue) { using (var enumerator = queue.GetMessageEnumerator2()) { return !enumerator.MoveNext(); } }
or implement Peek, which returns null if the message queue is empty (not tested, but should work)
private static Message Peek(MessageQueue queue) { using (var enumerator = queue.GetMessageEnumerator2()) { return enumerator.MoveNext() ? enumerator.Current : null; } }
We used a code similar to the original to check about twenty different queues. Since we changed the initial implementation to the one I propose, the speed of our import increased sharply, since the processor could be used more for processing messages instead of processing throws.
Oskar Sjöberg
source share