Clearing azure service bus queue in one go

bhavesh lad picture bhavesh lad · Mar 29, 2012 · Viewed 24.3k times · Source

We are using a service bus queue in our project. We are in need of a functionality to remove all the messages from the queue when the administrator chooses to clear the queue. I searched on the net but could not find any function which does this inside the QueueClient class.

Do I have to pop all the messages one by one and then marking them complete to clear the queue or is there a better way?

QueueClient queueClient = _messagingFactory.CreateQueueClient(
                              queueName, ReceiveMode.PeekLock);

BrokeredMessage brokeredMessage = queueClient.Receive();

while (brokeredMessage != null )
{
    brokeredMessage.Complete();
    brokeredMessage = queueClient.Receive();
}

Answer

Scott Brady picture Scott Brady · Feb 11, 2014

Using the Receive() method within the while loop like you are will cause your code to run indefinitely once the queue is empty, as the Receive() method will be waiting for another message to appear on the queue.

If you want this to run automatically, try using the Peek() method.

For example:

while (queueClient.Peek() != null)
{
    var brokeredMessage = queueClient.Receive();
    brokeredMessage.Complete();
}

You can make this simpler again with the ReceiveMode.ReceiveAndDelete as was mentioned by hocho.