透過 .NET 開始使用 Azure 佇列儲存體Get started with Azure Queue Storage using .NET

概觀Overview

Azure 佇列儲存體可提供應用程式元件之間的雲端通訊。Azure Queue Storage provides cloud messaging between application components. 設計應用程式以進行調整時,通常會將應用程式元件分離,讓它們可以獨立調整。In designing applications for scale, application components are often decoupled so they can scale independently. 佇列儲存體可提供應用程式元件之間的非同步訊息處理,不論它們是在雲端、桌面、內部部署伺服器或行動裝置上執行。Queue Storage delivers asynchronous messaging between application components, whether they are running in the cloud, on the desktop, on an on-premises server, or on a mobile device. 佇列儲存體也支援管理非同步工作和建立程式工作流程。Queue Storage also supports managing asynchronous tasks and building process work flows.

關於本教學課程About this tutorial

本教學課程說明如何使用 Azure 佇列儲存體撰寫一些常見案例的 .NET 程式碼。This tutorial shows how to write .NET code for some common scenarios using Azure Queue Storage. 本文說明的案例包括建立和刪除佇列,以及新增、讀取和刪除佇列訊息。Scenarios covered include creating and deleting queues and adding, reading, and deleting queue messages.

預估完成時間: 45 分鐘Estimated time to complete: 45 minutes

必要條件Prerequisites

什麼是佇列儲存體?What is Queue storage?

Azure 佇列儲存體是一項儲存大量訊息的服務,全球任何地方都可利用 HTTP 或 HTTPS 並透過驗證的呼叫來存取這些訊息。Azure Queue storage is a service for storing large numbers of messages that can be accessed from anywhere in the world via authenticated calls using HTTP or HTTPS. 單一佇列訊息的大小上限為 64 KB,而一個佇列可以包含數百萬個訊息,以儲存體帳戶的總容量為限。A single queue message can be up to 64 KB in size, and a queue can contain millions of messages, up to the total capacity limit of a storage account. 佇列儲存體通常用來建立要以非同步方式處理的待處理專案(backlog)。Queue storage is often used to create a backlog of work to process asynchronously.

佇列服務概念Queue service concepts

Azure 佇列服務包含下列元件:The Azure Queue service contains the following components:

Azure 佇列服務元件

  • 儲存體帳戶: Azure 儲存體的所有存取都是透過儲存體帳戶完成。Storage Account: All access to Azure Storage is done through a storage account. 如需儲存體帳戶的詳細資訊,請參閱儲存體帳戶概觀For more information about storage accounts, see Storage account overview.

  • 佇列: 佇列包含一組訊息。Queue: A queue contains a set of messages. 所有訊息都必須放在佇列中。All messages must be in a queue. 請注意,佇列名稱必須是小寫。Note that the queue name must be all lowercase. 如需為佇列命名的詳細資訊,請參閱 為佇列和中繼資料命名For information on naming queues, see Naming Queues and Metadata.

  • 訊息: 大小上限為 64 KB 的訊息 (任何格式)。Message: A message, in any format, of up to 64 KB. 訊息可保留在佇列中的時間上限為 7 天。The maximum time that a message can remain in the queue is 7 days. 如需版本 2017-07-29 或更新版本,最大存留時間可以是任何正數,或是表示訊息未過期的 -1。For version 2017-07-29 or later, the maximum time-to-live can be any positive number, or -1 indicating that the message doesn't expire. 如果省略此參數,則預設存留時間為 7 天。If this parameter is omitted, the default time-to-live is seven days.

  • URL 格式: 您可以使用下列 URL 格式來定址佇列: HTTP:// <storage account> . queue.core.windows.net/<queue>URL format: Queues are addressable using the following URL format: http://<storage account>.queue.core.windows.net/<queue>

    下列 URL 可定址圖中的佇列:The following URL addresses a queue in the diagram:

    http://myaccount.queue.core.windows.net/incoming-orders

建立 Azure 儲存體帳戶Create an Azure storage account

建立您第一個 Azure 儲存體帳戶最簡單的方法,就是使用 Azure 入口網站The easiest way to create your first Azure storage account is by using the Azure portal. 若要深入了解,請參閱 建立儲存體帳戶To learn more, see Create a storage account.

您也可以使用 Azure PowerShellAzure CLI,或 Azure Storage Resource Provider for .NET 來建立 Azure 儲存體帳戶。You can also create an Azure storage account by using Azure PowerShell, Azure CLI, or the Azure Storage Resource Provider for .NET.

如果您目前不想要在 Azure 中建立儲存體帳戶,您也可以使用 Azurite 儲存體模擬器在本機環境中執行並測試您的程式碼。If you prefer not to create a storage account in Azure at this time, you can also use the Azurite storage emulator to run and test your code in a local environment. 如需詳細資訊,請參閱 使用 Azurite 模擬器進行本機 Azure 儲存體開發For more information, see Use the Azurite emulator for local Azure Storage development.

設定開發環境Set up your development environment

接下來,在 Visual Studio 中設定您的開發環境,以便您開始嘗試本指南中的程式碼範例。Next, set up your development environment in Visual Studio so you're ready to try the code examples in this guide.

建立 Windows 主控台應用程式專案Create a Windows console application project

在 Visual Studio 中,建立新的 Windows 主控台應用程式。In Visual Studio, create a new Windows console application. 下列步驟說明如何在 Visual Studio 2019 中建立主控台應用程式。The following steps show you how to create a console application in Visual Studio 2019. 這些步驟類似其他 Visual Studio 版本中的步驟。The steps are similar in other versions of Visual Studio.

  1. 選取 檔案 > 新增 > 專案Select File > New > Project
  2. 選取 平臺 > 視窗Select Platform > Windows
  3. 選取 主控台應用程式 ( .NET Framework)Select Console App (.NET Framework)
  4. 選取 [下一步]Select Next
  5. 在 [ 專案名稱 ] 欄位中,輸入應用程式的名稱In the Project name field, enter a name for your application
  6. 選取 [建立] Select Create

本教學課程中的所有程式碼範例均可新增至您主控台應用程式的 Program.cs 檔案中的 Main() 方法。All code examples in this tutorial can be added to the Main() method of your console application's Program.cs file.

您可以在任何類型的 .NET 應用程式中使用 Azure 儲存體的用戶端程式庫,包括 Azure 雲端服務或 web 應用程式,以及桌面與行動應用程式。You can use the Azure Storage client libraries in any type of .NET application, including an Azure cloud service or web app, and desktop and mobile applications. 在本指南中,為求簡化,我們會使用主控台應用程式。In this guide, we use a console application for simplicity.

使用 NuGet 來安裝必要的封裝Use NuGet to install the required packages

您必須參考專案中的下列四個套件,才能完成本教學課程:You need to reference the following four packages in your project to complete this tutorial:

您可以使用 NuGet 來取得這些套件。You can use NuGet to obtain these packages. 請遵循這些步驟:Follow these steps:

  1. 方案總管 中的專案上按一下滑鼠右鍵,然後選擇 [ 管理 NuGet 套件]。Right-click your project in Solution Explorer, and choose Manage NuGet Packages.
  2. 選取 [流覽]Select Browse
  3. 在線上搜尋 Azure.Storage.Queues ,然後選取 [ 安裝 ] 以安裝 Azure 儲存體用戶端程式庫及其相依性。Search online for Azure.Storage.Queues, and select Install to install the Azure Storage client library and its dependencies. 這也會安裝 Azure。 Common 和 Azure Core 程式庫是佇列程式庫的相依性。This will also install the Azure.Storage.Common and Azure.Core libraries, which are dependencies of the queue library.
  4. 在線上搜尋 System.Configuration.ConfigurationManager ,然後選取 [ 安裝 ] 來安裝 Configuration Manager。Search online for System.Configuration.ConfigurationManager, and select Install to install the Configuration Manager.

決定您的目標環境Determine your target environment

有兩個環境選項可供您執行本指南中的範例︰You have two environment options for running the examples in this guide:

  • 您可以對雲端中的 Azure 儲存體帳戶執行您的程式碼。You can run your code against an Azure Storage account in the cloud.
  • 您可以針對 Azurite 儲存體模擬器執行您的程式碼。You can run your code against the Azurite storage emulator. Azurite 是在雲端中模擬 Azure 儲存體帳戶的本機環境。Azurite is a local environment that emulates an Azure Storage account in the cloud. Azurite 是在應用程式開發期間測試和偵測程式碼的免費選項。Azurite is a free option for testing and debugging your code while your application is under development. 模擬器會使用已知的帳戶和金鑰。The emulator uses a well-known account and key. 如需詳細資訊,請參閱 使用 Azurite 模擬器進行本機 Azure 儲存體開發和測試For more information, see Use the Azurite emulator for local Azure Storage development and testing.

注意

您可以選擇以儲存體模擬器為目標,以避免產生與 Azure 儲存體相關聯的任何費用。You can target the storage emulator to avoid incurring any costs associated with Azure Storage. 但是,如果您選擇以雲端中的 Azure 儲存體帳戶為目標,則執行本教學課程的成本將會是可忽略的。However, if you do choose to target an Azure Storage account in the cloud, costs for performing this tutorial will be negligible.

取得儲存體連接字串Get your storage connection string

適用于 .NET 的 Azure 儲存體用戶端程式庫支援使用儲存體連接字串來設定端點和認證,以存取儲存體服務。The Azure Storage client libraries for .NET support using a storage connection string to configure endpoints and credentials for accessing storage services. 如需詳細資訊,請參閱管理儲存體帳戶存取金鑰For more information, see Manage storage account access keys.

從 Azure 入口網站複製您的認證Copy your credentials from the Azure portal

範例程式碼需要授與對您儲存體帳戶的存取權。The sample code needs to authorize access to your storage account. 若要進行授權,您必須以連接字串的形式為應用程式提供您的儲存體帳戶認證。To authorize, you provide the application with your storage account credentials in the form of a connection string. 若要檢視您的儲存體帳戶認證:To view your storage account credentials:

  1. 瀏覽至 Azure 入口網站Navigate to the Azure portal.

  2. 找出您的儲存體帳戶。Locate your storage account.

  3. 在儲存體帳戶概觀的 [設定] 區段中,選取 [存取金鑰]。In the Settings section of the storage account overview, select Access keys. 您的帳戶存取金鑰隨即出現,此外也會顯示每個金鑰的完整連接字串。Your account access keys appear, as well as the complete connection string for each key.

  4. 尋找 [金鑰1] 下方的 [連接字串] 值,然後按一下 [複製] 按鈕來複製連接字串。Find the Connection string value under key1, and click the Copy button to copy the connection string. 在下一個步驟中,您會將連接字串值新增至環境變數。You will add the connection string value to an environment variable in the next step.

    顯示如何從 Azure 入口網站複製連接字串的螢幕擷取畫面

如需有關連接字串的詳細資訊,請參閱設定 Azure 儲存體的連接字串For more information about connection strings, see Configure a connection string to Azure Storage.

注意

儲存體帳戶金鑰很類似儲存體帳戶的根密碼。Your storage account key is similar to the root password for your storage account. 請務必小心保護您的儲存體帳戶金鑰。Always be careful to protect your storage account key. 請避免轉發給其他使用者、進行硬式編碼,或將它儲存在其他人可以存取的純文字檔案。Avoid distributing it to other users, hard-coding it, or saving it in a plain-text file that is accessible to others. 如果您認為金鑰可能遭到破解,請使用 Azure 入口網站重新產生金鑰。Regenerate your key by using the Azure portal if you believe it may have been compromised.

在組態檔中維護儲存體連接字串是最佳方式。The best way to maintain your storage connection string is in a configuration file. 若要設定連接字串,請從 Visual Studio 中的 [方案總管] 開啟 app.config 檔案。To configure your connection string, open the app.config file from Solution Explorer in Visual Studio. 加入 <appSettings> 此處所示元素的內容。Add the contents of the <appSettings> element shown here. connection-string將取代為您在入口網站中從儲存體帳戶複製的值:Replace connection-string with the value you copied from your storage account in the portal:

<configuration>
    <startup>
        <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.7.2" />
    </startup>
    <appSettings>
        <add key="StorageConnectionString" value="connection-string" />
    </appSettings>
</configuration>

例如,組態設定會如下顯示:For example, your configuration setting appears similar to:

<add key="StorageConnectionString" value="DefaultEndpointsProtocol=https;AccountName=storagesample;AccountKey=GMuzNHjlB3S9itqZJHHCnRkrokLkcSyW7yK9BRbGp0ENePunLPwBgpxV1Z/pVo9zpem/2xSHXkMqTHHLcx8XRA==EndpointSuffix=core.windows.net" />

若要以 Azurite 儲存體模擬器為目標,您可以使用對應到知名帳戶名稱和金鑰的快捷方式。To target the Azurite storage emulator, you can use a shortcut that maps to the well-known account name and key. 在此情況下,您的連接字串設定會是︰In that case, your connection string setting is:

<add key="StorageConnectionString" value="UseDevelopmentStorage=true" />

新增 using 指示詞Add using directives

將下列 using 指示詞新增至 Program.cs 檔案的開頭處:Add the following using directives to the top of the Program.cs file:

using System; // Namespace for Console output
using System.Configuration; // Namespace for ConfigurationManager
using System.Threading.Tasks; // Namespace for Task
using Azure.Storage.Queues; // Namespace for Queue storage types
using Azure.Storage.Queues.Models; // Namespace for PeekedMessage

建立佇列儲存體用戶端Create the Queue Storage client

QueueClient類別可讓您取出儲存在佇列儲存體中的佇列。The QueueClient class enables you to retrieve queues stored in Queue Storage. 以下是建立服務用戶端的其中一種方式:Here's one way to create the service client:

//-------------------------------------------------
// Create the queue service client
//-------------------------------------------------
public void CreateQueueClient(string queueName)
{
    // Get the connection string from app settings
    string connectionString = ConfigurationManager.AppSettings["StorageConnectionString"];

    // Instantiate a QueueClient which will be used to create and manipulate the queue
    QueueClient queueClient = new QueueClient(connectionString, queueName);
}

現在您已準備好撰寫程式碼,從佇列儲存體讀取資料,並將資料寫入佇列儲存體。Now you are ready to write code that reads data from and writes data to Queue Storage.

建立佇列Create a queue

此範例說明如何建立佇列:This example shows how to create a queue:

//-------------------------------------------------
// Create a message queue
//-------------------------------------------------
public bool CreateQueue(string queueName)
{
    try
    {
        // Get the connection string from app settings
        string connectionString = ConfigurationManager.AppSettings["StorageConnectionString"];

        // Instantiate a QueueClient which will be used to create and manipulate the queue
        QueueClient queueClient = new QueueClient(connectionString, queueName);

        // Create the queue
        queueClient.CreateIfNotExists();

        if (queueClient.Exists())
        {
            Console.WriteLine($"Queue created: '{queueClient.Name}'");
            return true;
        }
        else
        {
            Console.WriteLine($"Make sure the Azurite storage emulator running and try again.");
            return false;
        }
    }
    catch (Exception ex)
    {
        Console.WriteLine($"Exception: {ex.Message}\n\n");
        Console.WriteLine($"Make sure the Azurite storage emulator running and try again.");
        return false;
    }
}

將訊息插入佇列Insert a message into a queue

若要將訊息插入現有佇列中,請呼叫 SendMessage 方法。To insert a message into an existing queue, call the SendMessage method. 訊息可以是 UTF-8 格式的字串 () 或位元組陣列。A message can be either a string (in UTF-8 format) or a byte array. 下列程式碼會建立佇列 (如果它不存在) 並插入訊息:The following code creates a queue (if it doesn't exist) and inserts a message:

//-------------------------------------------------
// Insert a message into a queue
//-------------------------------------------------
public void InsertMessage(string queueName, string message)
{
    // Get the connection string from app settings
    string connectionString = ConfigurationManager.AppSettings["StorageConnectionString"];

    // Instantiate a QueueClient which will be used to create and manipulate the queue
    QueueClient queueClient = new QueueClient(connectionString, queueName);

    // Create the queue if it doesn't already exist
    queueClient.CreateIfNotExists();

    if (queueClient.Exists())
    {
        // Send a message to the queue
        queueClient.SendMessage(message);
    }

    Console.WriteLine($"Inserted: {message}");
}

查看下一個訊息Peek at the next message

您可以藉由呼叫方法來查看佇列中的訊息,而不需要將它們從佇列中移除 PeekMessagesYou can peek at the messages in the queue without removing them from the queue by calling the PeekMessages method. 如果您未傳遞參數的值 maxMessages ,則預設值是查看單一訊息。If you don't pass a value for the maxMessages parameter, the default is to peek at one message.

//-------------------------------------------------
// Peek at a message in the queue
//-------------------------------------------------
public void PeekMessage(string queueName)
{
    // Get the connection string from app settings
    string connectionString = ConfigurationManager.AppSettings["StorageConnectionString"];

    // Instantiate a QueueClient which will be used to manipulate the queue
    QueueClient queueClient = new QueueClient(connectionString, queueName);

    if (queueClient.Exists())
    { 
        // Peek at the next message
        PeekedMessage[] peekedMessage = queueClient.PeekMessages();

        // Display the message
        Console.WriteLine($"Peeked message: '{peekedMessage[0].MessageText}'");
    }
}

變更佇列訊息的內容Change the contents of a queued message

您可以在佇列中就地變更訊息內容。You can change the contents of a message in-place in the queue. 如果訊息代表工作作業,則您可以使用此功能來更新工作作業的狀態。If the message represents a work task, you could use this feature to update the status of the work task. 下列程式碼將使用新的內容更新佇列訊息,並將可見度逾時設定延長 60 秒。The following code updates the queue message with new contents, and sets the visibility timeout to extend another 60 seconds. 這可儲存與訊息相關的工作狀態,並提供用戶端多一分鐘的時間繼續處理訊息。This saves the state of work associated with the message, and gives the client another minute to continue working on the message. 您可以使用這項技術來追蹤佇列訊息上的多步驟工作流程,而不需要從頭開始(如果處理步驟因為硬體或軟體故障而失敗)。You could use this technique to track multistep workflows on queue messages, without having to start over from the beginning if a processing step fails due to hardware or software failure. 通常,您也會保留重試計數,如果訊息重試超過 n 次,您就會刪除它。Typically, you would keep a retry count as well, and if the message is retried more than n times, you would delete it. 這麼做可防止每次處理時便觸發應用程式錯誤的訊息。This protects against a message that triggers an application error each time it is processed.

//-------------------------------------------------
// Update an existing message in the queue
//-------------------------------------------------
public void UpdateMessage(string queueName)
{
    // Get the connection string from app settings
    string connectionString = ConfigurationManager.AppSettings["StorageConnectionString"];

    // Instantiate a QueueClient which will be used to manipulate the queue
    QueueClient queueClient = new QueueClient(connectionString, queueName);

    if (queueClient.Exists())
    {
        // Get the message from the queue
        QueueMessage[] message = queueClient.ReceiveMessages();

        // Update the message contents
        queueClient.UpdateMessage(message[0].MessageId, 
                message[0].PopReceipt, 
                "Updated contents",
                TimeSpan.FromSeconds(60.0)  // Make it invisible for another 60 seconds
            );
    }
}

將下一個訊息清除佇列Dequeue the next message

透過兩個步驟,從佇列中清除佇列中的訊息。Dequeue a message from a queue in two steps. 當您呼叫時 ReceiveMessages ,會取得佇列中的下一則訊息。When you call ReceiveMessages, you get the next message in a queue. ReceiveMessages 傳回的訊息,對於從此佇列讀取訊息的任何其他程式碼而言,將會是不可見的。A message returned from ReceiveMessages becomes invisible to any other code reading messages from this queue. 依預設,此訊息會維持 30 秒的不可見狀態。By default, this message stays invisible for 30 seconds. 若要完成從佇列中移除訊息,您還必須呼叫 DeleteMessageTo finish removing the message from the queue, you must also call DeleteMessage. 這個移除訊息的兩步驟程序可確保您的程式碼因為硬體或軟體故障而無法處理訊息時,另一個程式碼的執行個體可以取得相同訊息並再試一次。This two-step process of removing a message assures that if your code fails to process a message due to hardware or software failure, another instance of your code can get the same message and try again. 您的程式碼會在 DeleteMessage 處理完訊息之後立即呼叫。Your code calls DeleteMessage right after the message has been processed.

//-------------------------------------------------
// Process and remove a message from the queue
//-------------------------------------------------
public void DequeueMessage(string queueName)
{
    // Get the connection string from app settings
    string connectionString = ConfigurationManager.AppSettings["StorageConnectionString"];

    // Instantiate a QueueClient which will be used to manipulate the queue
    QueueClient queueClient = new QueueClient(connectionString, queueName);

    if (queueClient.Exists())
    {
        // Get the next message
        QueueMessage[] retrievedMessage = queueClient.ReceiveMessages();

        // Process (i.e. print) the message in less than 30 seconds
        Console.WriteLine($"Dequeued message: '{retrievedMessage[0].MessageText}'");

        // Delete the message
        queueClient.DeleteMessage(retrievedMessage[0].MessageId, retrievedMessage[0].PopReceipt);
    }
}

使用 Async-Await 模式搭配一般佇列儲存體 ApiUse the Async-Await pattern with common Queue Storage APIs

此範例說明如何搭配使用 Async-Await 模式與一般佇列儲存體 Api。This example shows how to use the Async-Await pattern with common Queue Storage APIs. 此範例會呼叫每個指定方法的非同步版本,如 Async 每個方法的尾碼所表示。The sample calls the asynchronous version of each of the given methods, as indicated by the Async suffix of each method. 使用非同步方法時,Async-Await 模式會暫停本機執行,直到呼叫完成為止。When an async method is used, the Async-Await pattern suspends local execution until the call completes. 這種行為可讓目前的執行緒執行其他工作,有助於避免發生效能瓶頸並提升應用程式的整體回應。This behavior allows the current thread to do other work, which helps avoid performance bottlenecks and improves the overall responsiveness of your application. 如需如何在 .NET 中使用 Async-Await 模式的詳細資訊,請參閱 Async 和 Await (C# 和 Visual Basic)For more details on using the Async-Await pattern in .NET, see Async and Await (C# and Visual Basic)

//-------------------------------------------------
// Perform queue operations asynchronously
//-------------------------------------------------
public async Task QueueAsync(string queueName)
{
    // Get the connection string from app settings
    string connectionString = ConfigurationManager.AppSettings["StorageConnectionString"];

    // Instantiate a QueueClient which will be used to manipulate the queue
    QueueClient queueClient = new QueueClient(connectionString, queueName);

    // Create the queue if it doesn't already exist
    await queueClient.CreateIfNotExistsAsync();

    if (await queueClient.ExistsAsync())
    {
        Console.WriteLine($"Queue '{queueClient.Name}' created");
    }
    else
    {
        Console.WriteLine($"Queue '{queueClient.Name}' exists");
    }

    // Async enqueue the message
    await queueClient.SendMessageAsync("Hello, World");
    Console.WriteLine($"Message added");

    // Async receive the message
    QueueMessage[] retrievedMessage = await queueClient.ReceiveMessagesAsync();
    Console.WriteLine($"Retrieved message with content '{retrievedMessage[0].MessageText}'");

    // Async delete the message
    await queueClient.DeleteMessageAsync(retrievedMessage[0].MessageId, retrievedMessage[0].PopReceipt);
    Console.WriteLine($"Deleted message: '{retrievedMessage[0].MessageText}'");

    // Async delete the queue
    await queueClient.DeleteAsync();
    Console.WriteLine($"Deleted queue: '{queueClient.Name}'");
}

使用清除佇列訊息的其他選項Use additional options for dequeuing messages

自訂從佇列中擷取訊息的方法有兩種。There are two ways you can customize message retrieval from a queue. 首先,您可以取得一批訊息 (最多 32 個)。First, you can get a batch of messages (up to 32). 其次,您可以設定較長或較短的可見度逾時,讓您的程式碼有較長或較短的時間可以完全處理每個訊息。Second, you can set a longer or shorter invisibility timeout, allowing your code more or less time to fully process each message.

下列程式碼範例會使用 ReceiveMessages 方法,在一個呼叫中取得20個訊息。The following code example uses the ReceiveMessages method to get 20 messages in one call. 接著其會使用 foreach 迴圈處理每個訊息。Then it processes each message using a foreach loop. 它也會將可見度逾時設定為每個訊息五分鐘。It also sets the invisibility timeout to five minutes for each message. 請注意,系統會同時為所有訊息啟動五分鐘的時間,因此,從呼叫以來經過五分鐘後 ReceiveMessages ,任何尚未刪除的訊息都會重新顯示。Note that the five minutes starts for all messages at the same time, so after five minutes have passed since the call to ReceiveMessages, any messages which have not been deleted will become visible again.

//-----------------------------------------------------
// Process and remove multiple messages from the queue
//-----------------------------------------------------
public void DequeueMessages(string queueName)
{
    // Get the connection string from app settings
    string connectionString = ConfigurationManager.AppSettings["StorageConnectionString"];

    // Instantiate a QueueClient which will be used to manipulate the queue
    QueueClient queueClient = new QueueClient(connectionString, queueName);

    if (queueClient.Exists())
    {
        // Receive and process 20 messages
        QueueMessage[] receivedMessages = queueClient.ReceiveMessages(20, TimeSpan.FromMinutes(5));

        foreach (QueueMessage message in receivedMessages)
        {
            // Process (i.e. print) the messages in less than 5 minutes
            Console.WriteLine($"De-queued message: '{message.MessageText}'");

            // Delete the message
            queueClient.DeleteMessage(message.MessageId, message.PopReceipt);
        }
    }
}

取得佇列長度Get the queue length

您可以取得佇列中的估計訊息數目。You can get an estimate of the number of messages in a queue. 方法會傳回 GetProperties 佇列屬性,包括訊息計數。The GetProperties method returns queue properties including the message count. ApproximateMessagesCount屬性包含佇列中大約的訊息數目。The ApproximateMessagesCount property contains the approximate number of messages in the queue. 此數目不會低於佇列中實際的訊息數目,而會更高。This number is not lower than the actual number of messages in the queue, but could be higher.

//-----------------------------------------------------
// Get the approximate number of messages in the queue
//-----------------------------------------------------
public void GetQueueLength(string queueName)
{
    // Get the connection string from app settings
    string connectionString = ConfigurationManager.AppSettings["StorageConnectionString"];

    // Instantiate a QueueClient which will be used to manipulate the queue
    QueueClient queueClient = new QueueClient(connectionString, queueName);

    if (queueClient.Exists())
    {
        QueueProperties properties = queueClient.GetProperties();

        // Retrieve the cached approximate message count.
        int cachedMessagesCount = properties.ApproximateMessagesCount;

        // Display number of messages.
        Console.WriteLine($"Number of messages in queue: {cachedMessagesCount}");
    }
}

刪除佇列Delete a queue

若要刪除佇列及其內含的所有訊息,請 Delete 在佇列物件上呼叫方法。To delete a queue and all the messages contained in it, call the Delete method on the queue object.

//-------------------------------------------------
// Delete the queue
//-------------------------------------------------
public void DeleteQueue(string queueName)
{
    // Get the connection string from app settings
    string connectionString = ConfigurationManager.AppSettings["StorageConnectionString"];

    // Instantiate a QueueClient which will be used to manipulate the queue
    QueueClient queueClient = new QueueClient(connectionString, queueName);

    if (queueClient.Exists())
    {
        // Delete the queue
        queueClient.Delete();
    }

    Console.WriteLine($"Queue deleted: '{queueClient.Name}'");
}

後續步驟Next steps

既然您已瞭解佇列儲存體的基本概念,請遵循下列連結以瞭解更複雜的儲存體工作。Now that you've learned the basics of Queue Storage, follow these links to learn about more complex storage tasks.