About
In this code snippet, we will learn how to queue, check and dequeue messages from Azure Queues using C#.
To quote Microsoft: “Azure Queue Storage is a service for storing large numbers of messages. You access messages from anywhere in the world via authenticated calls using HTTP or HTTPS. A queue message can be up to 64 KB in size. A queue may contain millions of messages, up to the total capacity limit of a storage account. Queues are commonly used to create a backlog of work to process asynchronously, like in the Web-Queue-Worker architectural style.”
Note: Additionally consider checking out Azure Service Bus messaging.
Note: You can use Azure Storage Explorer to inspect and edit queues manually.
Let’s see how to use Azure Queues with C# in the code examples below.
Prerequisites:
Before getting started you need to install the Azure Queues client library NuGet package into your project: Azure.Storage.Queues and add the following using statement at the top of your code file.
using Azure.Storage.Queues; using Azure.Storage.Queues.Models;
Next, you need to get the connection string to your storage account. You can find it if you go to the storage account in the Azure portal and select “Access Keys”. We will need this in the code snippets below.
Note: It’s a good idea to save it as an environmental variable an not hardcode it as a string.
Code:
public static async Task QueueOperationsAsync() { string connectionString = Environment.GetEnvironmentVariable("AzureWebJobsStorage");// "your_connection_string"; //Environment.GetEnvironmentVariable("AzureWebJobsStorage"); string queueName = "test"; //Create a QueueServiceClient. QueueServiceClient queueServiceClient = new QueueServiceClient(connectionString); //Create a reference to the queue. QueueClient queueClient = queueServiceClient.GetQueueClient(queueName); //Create the queue if it doesn't exist already. await queueClient.CreateIfNotExistsAsync(); //Add a message to the queue. string messageText = "Hello World!"; await queueClient.SendMessageAsync(messageText); //Peek at the message in the queue without removing it. PeekedMessage[] peekedMessages = await queueClient.PeekMessagesAsync(1); foreach (PeekedMessage peekedMessage in peekedMessages) { Console.WriteLine($"Peeked message: {peekedMessage.MessageText}"); } //Dequeue the message. QueueMessage[] retrievedMessages = await queueClient.ReceiveMessagesAsync(1); foreach (QueueMessage retrievedMessage in retrievedMessages) { //Process the message ... Console.WriteLine($"Message contents: {retrievedMessage.MessageText}, do something ..."); //After processing it we can delete it. await queueClient.DeleteMessageAsync(retrievedMessage.MessageId, retrievedMessage.PopReceipt); } }