Recently I had to create a demo demonstrating the Azure service bus message queues for an Azure Developer training on event and message-based messaging. For this simple demo, I needed to look up the number of messages on the queue and as it turned out, this was not the easiest code snippet to find.

There are a lot of implementations and code snippets on the older WindowsAzure.ServiceBus, but I was implementing Azure.Messaging.ServiceBus. In the old version active queue counts were exposed through the NameSpaceManager, but in the new version, service bus and queue management are done through the ServiceBusAdministrationClient requesting the QueueRuntimeProperties.

const string queueName = "[Name of queue]";
const string connectionString = "[Connectionstring of queue]";

public async Task<int> GetMessageQueueCountAsync()
{
    ServiceBusAdministrationClient client = new ServiceBusAdministrationClient(connectionString);

    QueueRuntimeProperties properties = await client.GetQueueRuntimePropertiesAsync(queueName);

    return (int)properties.TotalMessageCount;
}