Question

I'm using ActiveMQ to send and receive messages using a C# app. However I'm having some difficulty just getting a count of the messages in the queue.. Here's my code:

    public int GetMessageCount()
    {
        int messageCount = 0;
        Uri connecturi = new Uri(this.ActiveMQUri);

        IConnectionFactory factory = new NMSConnectionFactory(connecturi);

        using (IConnection connection = factory.CreateConnection())
        using (ISession session = connection.CreateSession())
        {
            IDestination requestDestination = SessionUtil.GetDestination(session, this.QueueRequestUri);

            IQueueBrowser queueBrowser = session.CreateBrowser((IQueue)requestDestination);
            IEnumerator messages = queueBrowser.GetEnumerator();

            while(messages.MoveNext())
            {
                messageCount++;
            }

            connection.Close();
            session.Close();
            connection.Close();
        }

        return messageCount;
    }

I thought I could use the QueueBrowser to get the count, but the IEnumerator it returns is always empty. I got the idea of using QueueBrowser from this page, but maybe there is another way I should be doing this?

Update:

The solution to the 'infinite loop' issue I found when going through the enumerator was solved by accessing the current message. It now only goes through the loop once (which is correct as there is only one message in the queue).

New while loop is:

while(messages.MoveNext())
{
    IMessage message = (IMessage)messages.Current;
    messageCount++;
}
Was it helpful?

Solution

I don't have an ActiveMq with me right now so I can not try it but I think the problem is you are not starting the connection. Try like this :

using (IConnection connection = factory.CreateConnection())
{
    connection.start ();

     using (ISession session = connection.CreateSession())
     {
      //Whatever...
     }

}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top