The first I thought I had when I read the question was why not delete and recreate the queue? That could be an approach. But if don't want to do that, you can receive and delete each message until there's no message left.
You can use the latest Azure Service Bus .NET library Azure.Messaging.ServiceBus for both approaches.
- Delete and recreate queue using
AdministrationClient
using Azure.Messaging.ServiceBus.Administration;
ServiceBusAdministrationClient adminClient = new ServiceBusAdministrationClient("<connectionstring>");
await adminClient.DeleteQueueAsync("myqueue");
await adminClient.CreateQueueAsync("myqueue");
Note: ServiceBusAdministrationClient
is for CRUD operations on an already existing Service Bus namespace. If you also need the ability to create a namespace, use the Microsoft.Azure.Management.ServiceBus library instead.
- Receive and delete until there's no message
using Azure.Messaging.ServiceBus;
await using var client = new ServiceBusClient("<connectionstring>");
ServiceBusReceiver receiver = client.CreateReceiver("myqueue",
new ServiceBusReceiverOptions { ReceiveMode = ServiceBusReceiveMode.ReceiveAndDelete });
while ((await receiver.PeekMessageAsync()) != null)
{
// receive in batches of 100 messages.
await receiver.ReceiveMessagesAsync(100);
}
ReceiveMode = ServiceBusReceiveMode.ReceiveAndDelete
is self-explanatory. The default receive mode is PeekLock
which doesn't actually remove messages from the queue - it tells Service Bus that the receiving client wants to settle the received messages explicitly. The lock part means competing receivers can't access the message for the duration of the lock.