As far as I can see from the documentation, the way you are supposed to check if there are messages in a message queue is to use the Peek method. You then rely on it failing with a MessageQueueException to tell you that the queue was empty.
public bool IsQueueEmpty()
{
bool isQueueEmpty = false;
MessageQueue myQueue = new MessageQueue(".\\myQueue");
try
{
myQueue.Peek(new TimeSpan(0));
isQueueEmpty = false;
}
catch(MessageQueueException e)
{
if (e.MessageQueueErrorCode ==
MessageQueueErrorCode.IOTimeout)
{
isQueueEmpty = true;
}
}
return isQueueEmpty;
}
I've always been told - and have experienced - that Exeptions are costly, and should not be used for normal operations. So my questions are:
Are my assumptions that relying on catching the MessageQueueException is a costly operation correct?
Are there any way to synchronously check if there are messages in a queue without having to rely on exceptions?
I'm working with the System.Messaging namespace in C#, but if I would need to go unmanaged to solve this that could be an option. And note that I want a solution without using WCF with MSMQ.