Azure Logo Azure Documentation

Send and Receive Messages with Azure Storage Queue

This tutorial will guide you through the process of sending messages to and receiving messages from an Azure Storage Queue using .NET.

Tip: Before you begin, ensure you have an Azure Storage account. If you don't have one, you can create a free account.

Prerequisites

Set up your development environment

To interact with Azure Storage Queue, you'll use the Azure SDK for .NET. First, create a new .NET console application:

dotnet new console -n AzureQueueSenderReceiver
cd AzureQueueSenderReceiver

Next, add the necessary NuGet packages:

dotnet add package Azure.Storage.Queues

Configure connection string

You'll need your storage account connection string. You can find this in the Azure portal under your storage account's "Access keys" section.

For this tutorial, we'll store the connection string in the application's configuration. You can use the appsettings.json file or environment variables.

Create a file named appsettings.json in your project's root directory:

{
  "AzureWebJobsStorage": "YOUR_CONNECTION_STRING"
}

Replace YOUR_CONNECTION_STRING with your actual storage account connection string.

Sending messages

Now, let's modify your Program.cs file to send messages to the queue. We'll create a queue if it doesn't exist, then add several messages.

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

// Placeholder for appsettings.json reading if you were building a full app.
// For this example, we'll hardcode the connection string.
// In a real app, use configuration providers.
string connectionString = Environment.GetEnvironmentVariable("AzureWebJobsStorage") ?? "YOUR_CONNECTION_STRING_HERE"; // Replace or use env var

// Replace with your queue name
string queueName = "my-sample-queue";

Console.WriteLine("Azure Queue Storage - Send Messages");

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

try
{
    // Create the queue if it doesn't exist
    await queueClient.CreateIfNotExistsAsync();
    Console.WriteLine($"Created queue '{queueName}' (if it existed).");

    // Send messages
    Console.WriteLine("\nSending messages...");
    await queueClient.SendMessageAsync("First message");
    await queueClient.SendMessageAsync("Second message");
    await queueClient.SendMessageAsync("Third message");
    Console.WriteLine("Messages sent.");
}
catch (Exception ex)
{
    Console.WriteLine($"Error: {ex.Message}");
}

Receiving messages

To receive messages, we'll peek at the messages in the queue without deleting them, and then receive and delete them. This simulates common message processing patterns.

Add the following code to your Program.cs file:

// --- Receiving Messages ---

Console.WriteLine("\nReceiving messages (peeking)...");

try
{
    // Peek at messages without deleting them
    var peekedMessages = await queueClient.PeekMessagesAsync(maxMessages: 5);
    if (peekedMessages.HasValue)
    {
        foreach (var peekedMessage in peekedMessages.Value)
        {
            Console.WriteLine($"Peeked Message: {peekedMessage.MessageText}");
        }
    }
    else
    {
        Console.WriteLine("No messages to peek.");
    }

    Console.WriteLine("\nReceiving messages (and deleting)...");

    // Receive and delete messages
    var receivedMessages = await queueClient.ReceiveMessagesAsync(maxMessages: 5);
    if (receivedMessages.HasValue)
    {
        foreach (var receivedMessage in receivedMessages.Value)
        {
            Console.WriteLine($"Received Message: {receivedMessage.MessageText}");
            // Delete the message after processing
            await queueClient.DeleteMessageAsync(receivedMessage.MessageId, receivedMessage.PopReceipt);
            Console.WriteLine($"Deleted message: {receivedMessage.MessageText}");
        }
    }
    else
    {
        Console.WriteLine("No messages to receive.");
    }
}
catch (Exception ex)
{
    Console.WriteLine($"Error receiving messages: {ex.Message}");
}

Run the application

Save your Program.cs and appsettings.json files. Before running, make sure to replace YOUR_CONNECTION_STRING_HERE in Program.cs with your actual connection string. You can also set it as an environment variable named AzureWebJobsStorage.

dotnet run

You should see output indicating that the queue was created (or already exists), messages were sent, peeked at, received, and deleted.

Note: When you ReceiveMessagesAsync, messages are invisible for a period (visibility timeout) and are deleted only after explicit deletion. If you don't delete them within the timeout, they become visible again.

Next Steps

Explore other Azure Storage Queue features: