Author : MD TAREQ HASSAN | Updated : 2020/10/23

Prerequisites

Dependency

Nuget

Install-Package Azure.Storage.Queues

Setup

appsettings.json (best way: put connection string in Azure KeyVault, see: Using Azure KeyVault in Production)

{
  "az_storage_account_connection_string": "DefaultEndpointsProtocol=https;AccountName=...;AccountKey=...;EndpointSuffix=core.windows.net",
  "az_queue_storage_name": "orders",
}

Constants.cs

public static class Constants
{
	public static readonly string KEY_AZURE_STORAGE_ACCOUNT_CONNECTION_STRING = "az_storage_account_connection_string";
	public static readonly string KEY_QUEUE_NAME = "az_queue_storage_name";
}

IQueueService.cs

public interface IQueueService
{
	Task SendMessageAsync<T>(T item);
}

AzureQueueService.cs

using Azure.Storage.Blobs;
using Azure.Storage.Blobs.Models;
using Microsoft.Extensions.Configuration;
using System.IO;
using System.Threading.Tasks;

namespace Foo.Services
{

    public class AzureQueueService : IQueueService
    {
        string azureStorageAccountConnectionString;
        string queueName;


        public AzureQueueService(IConfiguration configuration)
        {

            azureStorageAccountConnectionString = configuration[Constants.KEY_AZURE_STORAGE_ACCOUNT_CONNECTION_STRING];
            queueName = configuration[Constants.KEY_QUEUE_NAME];
        }

        public async Task SendMessageAsync<T>(T item)
        {
            string msgBody = JsonConvert.SerializeObject(item);

            QueueClient orderQueueClient = new QueueClient(azureStorageAccountConnectionString, queueName);

            // await orderQueueClient.CreateIfNotExistsAsync();

            await orderQueueClient.SendMessageAsync(msgBody);
        }
    }
}

Send messages

// Send a message to queue
AzureQueueService queueService; // get it by dependency injection (i.e. in ASP.NET Core app or in Blazor app)

await queueService.SendMessageAsync("hovermind"); // await QueueClient.SendMessageAsync("...");

Receive messages

QueueClient queueClient = new QueueClient(connectionString, queueName);
// Send messages: await QueueClient.SendMessageAsync("...");

// Get the next messages from the queue
foreach (QueueMessage message in queueClient.ReceiveMessages(maxMessages: 10).Value)
{
    // "Process" the message
    Console.WriteLine($"Message: {message.MessageText}");

    // Let the service know we're finished with the message and it can be safely deleted
    queue.DeleteMessage(message.MessageId, message.PopReceipt);
}

More operations

See: https://docs.microsoft.com/en-us/azure/storage/queues/storage-dotnet-how-to-use-queues?tabs=dotnet#create-a-queue