Stefano Terrana
Stefano Terrana

Reputation: 27

C# Azure Storage Queue - More efficient way to read messages from queue

I'm working on a API Web ASP.NET Core project with NET Core 5.0.0 and I'm using Azure.Storage.Queues 12.6.0 for writing and reading queue messages.

Everything works fine, but I was wondering if the way I read messages is OK or there is a better approach in terms of speed and efficiency.

This is the code I'm using. It's just a piece of code from a Microsoft tutorial, put inside a while() cycle. AzureQueue is just an instance of the QueueClient class.

    public async Task StartReading()
    {
        while (true)
        {
            if (await AzureQueue.ExistsAsync())
            {
                QueueProperties properties = await AzureQueue.GetPropertiesAsync();

                if (properties.ApproximateMessagesCount > 0)
                {
                    QueueMessage[] retrievedMessage = await AzureQueue.ReceiveMessagesAsync(1);
                    string theMessage = retrievedMessage[0].MessageText;
                    await AzureQueue.DeleteMessageAsync(retrievedMessage[0].MessageId, retrievedMessage[0].PopReceipt);
                }
            }
        }
    }

Honestly, I'm not comfortable using an infinte while() cycle, because it appears to me as something I can't control and stop. But my personal feelings apart, is this kind of while() an acceptable approach or I should use something else? I just need to continue reading messages immediately as they arrive into the queue.

Upvotes: 1

Views: 2776

Answers (1)

Shiraz Bhaiji
Shiraz Bhaiji

Reputation: 65391

What you can do is place your code in an Azure function.

Then bind the azure function to trigger when there is something on the queue.

See: https://learn.microsoft.com/en-us/azure/azure-functions/functions-bindings-storage-queue-trigger?tabs=csharp

Upvotes: 2

Related Questions