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(); }
You can simply do this from azure portal.
If you are not worried about queue messages stored in past 14 days (default) and wanted to clear queue immediately then change message time to live value to 5 or 10 seconds and wait for 5-10 seconds.
Important step: After a few seconds, try to receive from queue to force it to update.
All queue messages will be cleared. you can again reset original value. default is 14 days.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With