Clearing azure service bus queue in one go
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.
Using :
- Both approach (from @ScottBrady and @participant)
- And the MessageReceiver abstraction
you can write a method that empty a service bus queue or a topic/subscription:
MessageReceiver messageReceiver = ...while (messageReceiver.Peek() != null){ // Batch the receive operation var brokeredMessages = messageReceiver.ReceiveBatch(300); // Complete the messages var completeTasks = brokeredMessages.Select(m => Task.Run(() => m.Complete())).ToArray(); // Wait for the tasks to complete. Task.WaitAll(completeTasks);}
I'm having good results using a combination of ReceiveAndDelete, PrefetchCount, ReceiveBatchAsync, and a simple truth loop rather than using Peek. Example with MessagingFactory below:
var receiverFactory = MessagingFactory.CreateFromConnectionString("ConnString");var receiver = receiverFactory.CreateMessageReceiver("QName", ReceiveMode.ReceiveAndDelete);receiver.PrefetchCount = 300;bool loop = true;while (loop){ var messages = await receiver.ReceiveBatchAsync(300, TimeSpan.FromSeconds(1)); loop = messages.Any();}
Only requires the WindowsAzure.ServiceBus Nuget package.