How to Use Azure Storage Queues with .NET

Introduction

Azure Storage Queues is a service that enables you to store large numbers of messages that can be accessed from anywhere in the world. Queue messages are typically used to break application processing into asynchronous, loosely coupled components. This document provides instructions on how to use the Azure Storage Queue client library for .NET to interact with Azure Queues.

Prerequisites

Install the Azure Storage Queue Client Library for .NET

You can install the library using the NuGet Package Manager console or the .NET CLI.

NuGet Package Manager Console:
Install-Package Azure.Storage.Queues
.NET CLI:
dotnet add package Azure.Storage.Queues

Connect to the Azure Queue Service

To connect to your Azure Storage account and a specific queue, you'll need the connection string for your storage account. You can find this in the Azure portal under your storage account's "Access keys" section.

It's recommended to store your connection string securely, for example, using Azure Key Vault or user secrets in development.

Here's how to create a QueueClient object:


using Azure.Storage.Queues;
using System;

// Replace with your actual storage account connection string
string connectionString = "";
string queueName = "my-dotnet-queue";

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

// Optionally, create the queue if it doesn't exist
try
{
    queueClient.CreateIfNotExists();
    Console.WriteLine($"Queue '{queueName}' is ready.");
}
catch (Exception ex)
{
    Console.WriteLine($"Error creating or accessing queue: {ex.Message}");
}
            

Add a Message to a Queue

You can add a message to the queue using the SendMessage method. Messages can be strings or byte arrays. The message content has a size limit of 64 KB.


// Send a message to the queue
string messageContent = "Hello, Azure Queues!";
var response = await queueClient.SendMessageAsync(messageContent);

Console.WriteLine($"Message sent. Message ID: {response.Value.MessageId}");
            

Peek at a Message

Peeking at a message retrieves the next message in the queue without removing it. This is useful for inspecting messages without processing them.


// Peek at the next message in the queue
var peekResponse = await queueClient.PeekMessageAsync();

if (peekResponse.Value != null)
{
    Console.WriteLine($"Peeked message content: {peekResponse.Value.MessageText}");
}
else
{
    Console.WriteLine("Queue is empty.");
}
            

Dequeue a Message

Dequeuing a message retrieves and locks the next message in the queue, making it invisible to other clients for a specified visibility timeout. After processing, you must delete the message.


// Dequeue a message with a 30-second visibility timeout
var dequeueResponse = await queueClient.ReceiveMessageAsync();

if (dequeueResponse.Value != null)
{
    var message = dequeueResponse.Value;
    Console.WriteLine($"Dequeued message: {message.MessageText}");
    Console.WriteLine($"Message ID: {message.MessageId}");
    Console.WriteLine($"Pop receipt: {message.PopReceipt}");

    // Process the message here...

    // After processing, delete the message
    await queueClient.DeleteMessageAsync(message.MessageId, message.PopReceipt);
    Console.WriteLine("Message deleted.");
}
else
{
    Console.WriteLine("Queue is empty or no messages available.");
}
            

Delete a Message

After a message has been successfully processed, it must be explicitly deleted from the queue using its MessageId and PopReceipt.


// Assuming you have the message details from dequeueing
// await queueClient.DeleteMessageAsync(messageId, popReceipt);
            

Clear a Queue

You can clear all messages from a queue at once.


await queueClient.ClearMessagesAsync();
Console.WriteLine("Queue cleared.");
            

Manage Queues

The QueueClient also allows you to perform administrative operations on queues, such as getting properties or deleting the queue.


// Get queue properties
var properties = await queueClient.GetPropertiesAsync();
Console.WriteLine($"Queue count: {properties.Value.ApproximateMessagesCount}");

// Delete the queue (use with caution!)
// await queueClient.DeleteAsync();
// Console.WriteLine("Queue deleted.");
            

Deleting a queue permanently removes it and all its contents. Ensure you have backups or appropriate measures in place before performing this action.

Next Steps

For more detailed information and advanced scenarios, refer to the official Azure Queue Storage documentation.