Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Azure Service Bus: ReceiveMessagesAsync returns only a subset

I wrote a code to read 1000 messages one shot from an Azure Service Bus queue. I read the messages with the line: await receiver.ReceiveMessagesAsync(1000); but only a subset of the messages are received.

I took the code from the sample: https://github.com/Azure/azure-sdk-for-net/blob/main/sdk/servicebus/Azure.Messaging.ServiceBus/tests/Samples/Sample01_HelloWorld.cs, the SendAndReceiveMessageSafeBatch() method

This is my code:

public class Program
{
    static void Main(string[] args)
    {
        SendAndReceiveMessage().GetAwaiter().GetResult();
    }

    public static async Task SendAndReceiveMessage()
    {
        var connectionString = "myconnectionstring";
        var queueName = "myqueue";

        // since ServiceBusClient implements IAsyncDisposable we create it with "await using"
        await using var client = new ServiceBusClient(connectionString);

        // create the sender
        var sender = client.CreateSender(queueName);

        IList<ServiceBusMessage> messages = new List<ServiceBusMessage>();
        for (var i = 0; i < 1000; i++)
        {
            messages.Add(new ServiceBusMessage($"Message {i}"));
        }

        // send the messages
        await sender.SendMessagesAsync(messages);

        // create a receiver that we can use to receive the messages
        var options = new ServiceBusReceiverOptions()
        {
            ReceiveMode = ServiceBusReceiveMode.ReceiveAndDelete
        };

        ServiceBusReceiver receiver = client.CreateReceiver(queueName, options);

        // the received message is a different type as it contains some service set properties
        IReadOnlyList<ServiceBusReceivedMessage> receivedMessages = await receiver.ReceiveMessagesAsync(1000);

        Console.WriteLine($"Received {receivedMessages.Count} from the queue {queueName}");

        foreach (ServiceBusReceivedMessage receivedMessage in receivedMessages)
        {
            var body = receivedMessage.Body.ToString();
            Console.WriteLine(body);
        }

        Console.WriteLine("END");
        Console.ReadLine();
    }
}

Do you have any suggestion how to read all 1000 messages one shot?

like image 934
M-S Avatar asked Oct 25 '25 08:10

M-S


1 Answers

This is expected behaviour with Azure Service Bus. The number of messages to receive, maxMessages is a maximum number that is not guaranteed.

like image 66
Sean Feldman Avatar answered Oct 27 '25 21:10

Sean Feldman



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!