tags:

views:

400

answers:

3

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.

A: 

Update: I don't claim that performance is not important. But I think that inter process communication is very expensive in comparison to exception.

Before update:

  • I think that in the context of inter process communication( which is what msmq does) the cost of exception is unimportant. Test if you want to be sure.
  • I don't think so.
Igal Serban
We pass messages through a pipeline of services where we use queues between them. We want to have the highest throughput possible, so it's not unimportant, but so far we have good enough performance.
Torbjørn
I'll wait to see if I get any other comments, but if I don't I'll accept your answer :|
Torbjørn
A: 

MSMQ is not entirely interprocess communication. Interprocess communication is mostly in single machine but msmq can be used for different computers communicating. Guarenteed delivery, with flipside of having in same OS.

ebeworld
A: 

how about trying mq.GetAllMessages().Length> 0

Phani