Remove all messages from an Azure Service Bus Queue

Summary

There isn’t an official way or method to empty an Azure Service Bus Queue using the Nuget assemblies. The following approach loops through the message list and empties the contents from a Queue.

internal static async Task EntitiesQueue(string connectionString, string queueName)
        {
            client = new ServiceBusClient(connectionString);
            sender = client.CreateSender(queueName);

            // Delete the ServiceBus Queue
            ServiceBusReceiver receiver = client.CreateReceiver(queueName,
            new ServiceBusReceiverOptions { ReceiveMode = ServiceBusReceiveMode.ReceiveAndDelete });

            while ((await receiver.PeekMessageAsync()) != null)
            {
                // receive in batches of 100 messages.
                await receiver.ReceiveMessagesAsync(100);
            }

            // create a batch
            using ServiceBusMessageBatch messageBatch = await sender.CreateMessageBatchAsync();

            foreach (var result in Collections._GlobalEntityCol)
            {
                // try adding a message to the batch
                if (!messageBatch.TryAddMessage(new ServiceBusMessage($"{result["logicalname"]}")))
                {
                    // if it is too large for the batch
                    throw new Exception($"The message {result["logicalname"]} is too large to fit in the batch.");
                }
            }

            try
            {
                // Use the producer client to send the batch of messages to the Service Bus queue
                await sender.SendMessagesAsync(messageBatch);
                Console.WriteLine($"A batch of {numOfMessages} messages has been published to the queue.");
            }
            finally
            {
                // Calling DisposeAsync on client types is required to ensure that network resources
                // and other unmanaged objects are properly cleaned up.
                await sender.DisposeAsync();
                await client.DisposeAsync();
            }
        }

The code responsible for deleting all contents of a Queue

            // Delete the ServiceBus Queue
            ServiceBusReceiver receiver = client.CreateReceiver(queueName,
            new ServiceBusReceiverOptions { ReceiveMode = ServiceBusReceiveMode.ReceiveAndDelete });

            while ((await receiver.PeekMessageAsync()) != null)
            {
                // receive in batches of 100 messages.
                await receiver.ReceiveMessagesAsync(100);
            }

You must be logged in to post a comment.