Share via


Checking MSMQ message queue count with C#

I noticed the other day a team member was having exceptions being thrown every second when idle in a service.  Digging deeper it was revealed that the MSMQ Distributor has some code that peeks into a queue to determine if to process messages in the Enterprise Library logging framework.  I devised I think a better way to check for the number of messages and then process. What do you think or do you have a better way?

Snippet of offending code (generates exception when queue is empty)

            try
            {
                using (MessageQueue msmq = CreateMessageQueue())
                {
                    msmq.Peek(new TimeSpan(0));
                }
            }
            catch (MessageQueueException e)
            {
                if (e.MessageQueueErrorCode == MessageQueueErrorCode.IOTimeout)
                {
                    empty = true;
                }
            }

A Better Way?

 // Set the filter to only retrieve no major attributes or body
        MessagePropertyFilter propFilter = new MessagePropertyFilter();
        propFilter.ClearAll();
                
        MessageQueue newQueue = new MessageQueue(queuePath, false, true, QueueAccessMode.Peek);
        newQueue.MessageReadPropertyFilter = propFilter;

        if(newQueue.GetAllMessages().Length > 0)
               ...