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++;
}