Microsoft Docs

Get started with Azure Storage Queues

Azure Storage Queues provides a simple, reliable, and cost-effective way to decouple application components. Messages can be large (up to 64 KB), and a queue can contain any number of messages. The total storage required is just the size of the messages in the queue.

What are Azure Storage Queues?

Azure Storage Queues is a service that allows you to store large numbers of messages that can be accessed from anywhere in the world via HTTP or HTTPS. A queue is a collection of messages. Each message is stored in the queue until the application processing it successfully deletes it.

Key features include:

  • Scalability: Handles a virtually unlimited number of messages.
  • Decoupling: Allows different parts of an application to communicate asynchronously.
  • Reliability: Messages persist until explicitly deleted.
  • Cost-effectiveness: Pay only for the messages stored and operations performed.

Prerequisites

Before you begin, ensure you have the following:

Create a Queue and Send Messages

This section demonstrates how to create a queue and add messages using the Azure SDK for .NET.

Step 1: Install the Azure Storage Queues NuGet Package

Use the NuGet Package Manager or the .NET CLI to install the necessary package:

dotnet add package Azure.Storage.Queues

Step 2: Write Code to Interact with the Queue

Create a new C# file (e.g., Program.cs) and add the following code. Replace YOUR_CONNECTION_STRING with your actual storage account connection string.

using Azure.Storage.Queues;
using System;
using System.Threading.Tasks;

public class QueueDemo
{
    public static async Task Main(string[] args)
    {
        // Replace with your actual storage account connection string
        string connectionString = "YOUR_CONNECTION_STRING";
        string queueName = "my-sample-queue";

        // Create a new QueueClient
        QueueClient queueClient = new QueueClient(connectionString, queueName);

        try
        {
            // Create the queue if it doesn't exist
            await queueClient.CreateIfNotExistsAsync();
            Console.WriteLine($"Queue '{queueName}' created or already exists.");

            // Send a message to the queue
            string messageContent = "Hello from Azure Storage Queues!";
            await queueClient.SendMessageAsync(messageContent);
            Console.WriteLine($"Message sent: '{messageContent}'");

            // Send another message
            await queueClient.SendMessageAsync("This is the second message.");
            Console.WriteLine("Second message sent.");

        }
        catch (Exception ex)
        {
            Console.WriteLine($"An error occurred: {ex.Message}");
        }
    }
}

Step 3: Run the Application

Execute the application from your terminal:

dotnet run

You should see output indicating that the queue was created and messages were sent.

Receive and Process Messages

Now, let's add code to retrieve and process messages from the queue.

using Azure.Storage.Queues;
using Azure.Storage.Queues.Models;
using System;
using System.Threading.Tasks;

public class QueueReceiver
{
    public static async Task Main(string[] args)
    {
        // Replace with your actual storage account connection string
        string connectionString = "YOUR_CONNECTION_STRING";
        string queueName = "my-sample-queue";

        // Create a new QueueClient
        QueueClient queueClient = new QueueClient(connectionString, queueName);

        if (await queueClient.ExistsAsync())
        {
            Console.WriteLine($"Receiving messages from queue: '{queueName}'");

            // Peek at messages without removing them
            PeekMessagesResult peekResult = await queueClient.PeekMessagesAsync(maxMessages: 5);
            Console.WriteLine("\n--- Peeking at messages ---");
            foreach (QueueMessage message in peekResult.Messages)
            {
                Console.WriteLine($"Peeked Message: {message.MessageText}");
            }

            // Receive and delete messages
            ReceiveMessagesResult receiveResult = await queueClient.ReceiveMessagesAsync(maxMessages: 5);
            Console.WriteLine("\n--- Receiving and deleting messages ---");
            foreach (QueueMessage message in receiveResult.Messages)
            {
                Console.WriteLine($"Received Message: {message.MessageText}");
                // Process the message here...
                Console.WriteLine($"Processing message with ID: {message.MessageId}");

                // Delete the message from the queue
                await queueClient.DeleteMessageAsync(message.MessageId, message.PopReceipt);
                Console.WriteLine($"Message with ID {message.MessageId} deleted.");
            }
        }
        else
        {
            Console.WriteLine($"Queue '{queueName}' does not exist.");
        }
    }
}

Run this receiver application. It will attempt to read and delete messages that were sent previously.

Next Steps

Congratulations! You've successfully created and interacted with an Azure Storage Queue. Here are some resources to learn more: