通过 .NET 开始使用 Azure 队列存储Get started with Azure Queue storage using .NET

Tip

查看 Azure 存储代码示例存储库Check out the Azure Storage code samples repository

若要获取能够下载和运行且易于使用的端到端 Azure 存储代码,请查看我们提供的 Azure 存储示例列表。For easy-to-use end-to-end Azure Storage code samples that you can download and run, please check out our list of Azure Storage Samples.

概述Overview

Azure 队列存储用于在应用程序组件之间进行云消息传送。Azure Queue storage provides cloud messaging between application components. 在设计应用程序以实现可伸缩性时,通常要将各个应用程序组件分离,使其可以独立地进行伸缩。In designing applications for scale, application components are often decoupled, so that they can scale independently. 队列存储提供的异步消息传送适用于在应用程序组件之间进行通信,无论这些应用程序组件是运行在云中、桌面上、本地服务器上还是移动设备上。Queue storage delivers asynchronous messaging for communication 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.

队列存储的常见用途包括:Common uses of Queue storage include:

  • 创建积压工作以进行异步处理Creating a backlog of work to process asynchronously
  • 将消息从 Azure Web 角色传递到 Azure 辅助角色Passing messages from an Azure web role to an Azure worker role

队列服务概念Queue Service Concepts

队列服务包含以下组件:The Queue service contains the following components:

队列 1

  • URL 格式: 可使用以下 URL 格式对队列进行寻址:URL format: Queues are addressable using the following URL format:
    http://<storage account>.queue.core.chinacloudapi.cn/<queue>http://<storage account>.queue.core.chinacloudapi.cn/<queue>

    可使用以下 URL 访问示意图中的某个队列:The following URL addresses a queue in the diagram:

    http://myaccount.queue.core.chinacloudapi.cn/images-to-download

  • 存储帐户: 对 Azure 存储进行的所有访问都要通过存储帐户完成。Storage Account: All access to Azure Storage is done through a storage account. 有关存储帐户容量的详细信息,请参阅 Azure 存储可伸缩性和性能目标See Azure Storage Scalability and Performance Targets for details about storage account capacity.

  • 队列: 一个队列包含一组消息。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.

创建 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适用于 .NET 的 Azure 存储资源提供程序创建 Azure 存储帐户。You can also create an Azure storage account by using Azure PowerShell, Azure CLI, or the Azure Storage Resource Provider for .NET.

如果暂时不想在 Azure 中创建存储帐户,也可以使用 Azure 存储模拟器在本地环境中运行和测试代码。If you prefer not to create a storage account in Azure at this time, you can also use the Azure storage emulator to run and test your code in a local environment. 有关详细信息,请参阅 使用 Azure 存储模拟器进行开发和测试For more information, see Use the Azure Storage Emulator for Development and Testing.

设置开发环境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 2017 中创建控制台应用程序。The following steps show you how to create a console application in Visual Studio 2017. 在其他版本的 Visual Studio 中,这些步骤是类似的。The steps are similar in other versions of Visual Studio.

  1. 选择“文件” > “新建” > “项目”。Select File > New > Project.
  2. 选择“已安装” > “模板” > “Visual C#” > “Windows 经典桌面”。Select Installed > Templates > Visual C# > Windows Classic Desktop.
  3. 选择“控制台应用(.NET Framework)”。Select Console App (.NET Framework).
  4. 在“名称”字段中输入应用程序的名称。In the Name field, enter a name for your application.
  5. 选择“确定” 。Select OK.

Visual Studio 中“新建项目”对话框的屏幕截图

本教程中的所有代码示例都可以添加到控制台应用程序的 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 云服务或 Web 应用,以及桌面和移动应用程序)中使用 Azure 存储客户端库。You can use the Azure Storage Client Library 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

为完成此教程,需要在项目中引用两个包:There are two packages you need to reference in your project to complete this tutorial:

可以使用 NuGet 获取这两个包。You can use NuGet to obtain both packages. 执行以下步骤:Follow these steps:

  1. 在“解决方案资源管理器”中,右键单击项目并选择“管理 NuGet 包”。Right-click your project in Solution Explorer, and choose Manage NuGet Packages.
  2. 在线搜索“WindowsAzure.Storage”,并选择“安装”以安装存储客户端库和依赖项。Search online for "WindowsAzure.Storage", and select Install to install the Storage Client Library and its dependencies.
  3. 在线搜索“WindowsAzure.ConfigurationManager”,并选择“安装”以安装 Azure Configuration Manager。Search online for "WindowsAzure.ConfigurationManager", and select Install to install the Azure Configuration Manager.

Note

用于 .NET 的 Azure SDK中也包含存储客户端库包。The Storage Client Library package is also included in the Azure SDK for .NET. 但是我们建议同时从 NuGet 安装存储客户端库,以确保始终使用客户端库的最新版本。However, we recommend that you also install the Storage Client Library from NuGet to ensure that you always have the latest version of the client library.

适用于 .NET 的存储客户端库中的 ODataLib 依赖项通过 NuGet(而非 WCF 数据服务)上提供的 ODataLib 包来解析。The ODataLib dependencies in the Storage Client Library for .NET are resolved by the ODataLib packages available on NuGet, not from WCF Data Services. ODataLib 库可直接下载或者通过 NuGet 由代码项目引用。The ODataLib libraries can be downloaded directly, or referenced by your code project through NuGet. 存储空间客户端库使用的具体 ODataLib 包是 ODataEdmSpatialThe specific ODataLib packages used by the Storage Client Library are OData, Edm, and Spatial. 尽管这些库由 Azure 表存储类使用,但是用存储空间客户端库进行编程时,它们是必需的依赖项。While these libraries are used by the Azure Table storage classes, they are required dependencies for programming with the Storage Client Library.

确定目标环境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.
  • 可针对 Azure 存储模拟器运行代码。You can run your code against the Azure storage emulator. 存储模拟器是模拟云中 Azure 存储帐户的本地环境。The storage emulator is a local environment that emulates an Azure Storage account in the cloud. 应用程序处于开发阶段时,可以选择使用模拟器免费测试和调试代码。The emulator 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. 有关详细信息,请参阅使用 Azure 存储模拟器进行开发和测试For more information, see Use the Azure storage emulator for development and testing.

如果以云中的存储帐户为目标,请从 Azure 门户复制存储帐户的主访问密钥。If you are targeting a storage account in the cloud, copy the primary access key for your storage account from the Azure portal. 有关详细信息,请参阅访问密钥For more information, see Access keys.

Note

可以指向存储模拟器以避免引发与 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.

配置存储连接字符串Configure your storage connection string

用于 .NET 的 Azure 存储客户端库支持使用存储连接字符串来配置终结点和用于访问存储服务的凭据。The Azure Storage Client Library for .NET supports using a storage connection string to configure endpoints and credentials for accessing storage services. 维护存储连接字符串的最佳方法在配置文件中。The best way to maintain your storage connection string is in a configuration file.

有关连接字符串的详细信息,请参阅配置 Azure 存储的连接字符串For more information about connection strings, see Configure a connection string to Azure Storage.

Note

存储帐户密钥类似于存储帐户的根密码。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.

若要配置连接字符串,请从 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 below. account-name 替换为存储帐户名称,将 account-key 替换为存储帐户密钥:Replace account-name with the name of your storage account, and account-key with your account access key:

<configuration>
    <startup> 
        <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5.2" />
    </startup>
    <appSettings>
        <add key="StorageConnectionString" value="DefaultEndpointsProtocol=https;AccountName=account-name;AccountKey=account-key;EndpointSuffix=core.chinacloudapi.cn" />
    </appSettings>
</configuration>

例如,配置设置看起来类似于:For example, your configuration setting appears similar to:

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

若要以存储模拟器为目标,可使用映射到已知帐户名称和密钥的快捷方式。To target the 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 Microsoft.Azure; // Namespace for CloudConfigurationManager
using Microsoft.WindowsAzure.Storage; // Namespace for CloudStorageAccount
using Microsoft.WindowsAzure.Storage.Queue; // Namespace for Queue storage types

从 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 门户复制连接字符串的屏幕截图

解析连接字符串Parse the connection string

适用于 .NET 的 Azure Configuration Manager 库 提供用于分析配置文件中连接字符串的类。The Azure Configuration Manager Library for .NET provides a class for parsing a connection string from a configuration file. CloudConfigurationManager 类分析配置设置,而不考虑客户端应用程序是在台式计算机、移动设备、Azure 虚拟机还是 Azure 云服务中运行。The CloudConfigurationManager class parses configuration settings regardless of whether the client application is running on the desktop, on a mobile device, in an Azure virtual machine, or in an Azure cloud service.

若要引用 CloudConfigurationManager 包,请添加以下 using 指令:To reference the CloudConfigurationManager package, add the following using directive:

using Microsoft.Azure; //Namespace for CloudConfigurationManager
using Microsoft.WindowsAzure.Storage;

以下示例演示如何从配置文件中检索连接字符串:Here's an example that shows how to retrieve a connection string from a configuration file:

// Parse the connection string and return a reference to the storage account.
CloudStorageAccount storageAccount = CloudStorageAccount.Parse(
    CloudConfigurationManager.GetSetting("StorageConnectionString"));

不一定非要使用 Azure 配置管理器。Using the Azure Configuration Manager is optional. 也可以使用 API,例如 .NET Framework 的 ConfigurationManager 类。You can also use an API like the .NET Framework's ConfigurationManager class.

创建队列服务客户端Create the Queue service client

使用 CloudQueueClient 类可以检索存储在队列存储中的队列。The CloudQueueClient class enables you to retrieve queues stored in Queue storage. 下面是创建服务客户端的一种方法:Here's one way to create the service client:

CloudQueueClient queueClient = storageAccount.CreateCloudQueueClient();

现在,已准备好编写从队列存储读取数据并将数据写入队列存储的代码。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 if it does not already exist:

// Retrieve storage account from connection string.
CloudStorageAccount storageAccount = CloudStorageAccount.Parse(
    CloudConfigurationManager.GetSetting("StorageConnectionString"));

// Create the queue client.
CloudQueueClient queueClient = storageAccount.CreateCloudQueueClient();

// Retrieve a reference to a container.
CloudQueue queue = queueClient.GetQueueReference("myqueue");

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

在队列中插入消息Insert a message into a queue

要将消息插入现有队列,请先创建一个新的 CloudQueueMessageTo insert a message into an existing queue, first create a new CloudQueueMessage. 接下来,调用 AddMessage 方法。Next, call the AddMessage method. 可从字符串(UTF-8 格式)或字节数组创建 CloudQueueMessageA CloudQueueMessage can be created from either a string (in UTF-8 format) or a byte array. 以下代码创建队列(如果该队列不存在)并插入消息“Hello, World”:Here is code which creates a queue (if it doesn't exist) and inserts the message 'Hello, World':

// Retrieve storage account from connection string.
CloudStorageAccount storageAccount = CloudStorageAccount.Parse(
    CloudConfigurationManager.GetSetting("StorageConnectionString"));

// Create the queue client.
CloudQueueClient queueClient = storageAccount.CreateCloudQueueClient();

// Retrieve a reference to a queue.
CloudQueue queue = queueClient.GetQueueReference("myqueue");

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

// Create a message and add it to the queue.
CloudQueueMessage message = new CloudQueueMessage("Hello, World");
queue.AddMessage(message);

扫视下一条消息Peek at the next message

通过调用 PeekMessage 方法,可以速览队列前面的消息,而不必从队列中将其删除。You can peek at the message in the front of a queue without removing it from the queue by calling the PeekMessage method.

// Retrieve storage account from connection string
CloudStorageAccount storageAccount = CloudStorageAccount.Parse(
    CloudConfigurationManager.GetSetting("StorageConnectionString"));

// Create the queue client
CloudQueueClient queueClient = storageAccount.CreateCloudQueueClient();

// Retrieve a reference to a queue
CloudQueue queue = queueClient.GetQueueReference("myqueue");

// Peek at the next message
CloudQueueMessage peekedMessage = queue.PeekMessage();

// Display message.
Console.WriteLine(peekedMessage.AsString);

更改已排队消息的内容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 multi-step 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.

// Retrieve storage account from connection string.
CloudStorageAccount storageAccount = CloudStorageAccount.Parse(
    CloudConfigurationManager.GetSetting("StorageConnectionString"));

// Create the queue client.
CloudQueueClient queueClient = storageAccount.CreateCloudQueueClient();

// Retrieve a reference to a queue.
CloudQueue queue = queueClient.GetQueueReference("myqueue");

// Get the message from the queue and update the message contents.
CloudQueueMessage message = queue.GetMessage();
message.SetMessageContent("Updated contents.");
queue.UpdateMessage(message,
    TimeSpan.FromSeconds(60.0),  // Make it invisible for another 60 seconds.
    MessageUpdateFields.Content | MessageUpdateFields.Visibility);

取消对下一条消息的排队De-queue the next message

代码通过两个步骤来取消对队列中某条消息的排队。Your code de-queues a message from a queue in two steps. 调用 GetMessage时,你会获取队列中的下一条消息。When you call GetMessage, you get the next message in a queue. GetMessage 返回的消息变得对从此队列读取消息的任何其他代码不可见。A message returned from GetMessage 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. 代码在处理消息后会立即调用 DeleteMessageYour code calls DeleteMessage right after the message has been processed.

// Retrieve storage account from connection string
CloudStorageAccount storageAccount = CloudStorageAccount.Parse(
    CloudConfigurationManager.GetSetting("StorageConnectionString"));

// Create the queue client
CloudQueueClient queueClient = storageAccount.CreateCloudQueueClient();

// Retrieve a reference to a queue
CloudQueue queue = queueClient.GetQueueReference("myqueue");

// Get the next message
CloudQueueMessage retrievedMessage = queue.GetMessage();

//Process the message in less than 30 seconds, and then delete the message
queue.DeleteMessage(retrievedMessage);

将 Async-Await 模式与公用队列存储 API 配合使用Use 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)

// Create the queue if it doesn't already exist
if(await queue.CreateIfNotExistsAsync())
{
    Console.WriteLine("Queue '{0}' Created", queue.Name);
}
else
{
    Console.WriteLine("Queue '{0}' Exists", queue.Name);
}

// Create a message to put in the queue
CloudQueueMessage cloudQueueMessage = new CloudQueueMessage("My message");

// Async enqueue the message
await queue.AddMessageAsync(cloudQueueMessage);
Console.WriteLine("Message added");

// Async dequeue the message
CloudQueueMessage retrievedMessage = await queue.GetMessageAsync();
Console.WriteLine("Retrieved message with content '{0}'", retrievedMessage.AsString);

// Async delete the message
await queue.DeleteMessageAsync(retrievedMessage);
Console.WriteLine("Deleted message");

使用其他方法取消对消息的排队Leverage additional options for de-queuing 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. 以下代码示例使用 GetMessages 方法在一次调用中获取 20 条消息。The following code example uses the GetMessages method to get 20 messages in one call. 然后,它使用 foreach 循环处理每条消息。Then it processes each message using a foreach loop. 它还将每条消息的不可见超时时间设置为 5 分钟。It also sets the invisibility timeout to five minutes for each message. 请注意,5 分钟超时时间对于所有消息都是同时开始的,因此在调用 GetMessages5 分钟后,尚未删除的任何消息都会再次变得可见。Note that the 5 minutes starts for all messages at the same time, so after 5 minutes have passed since the call to GetMessages, any messages which have not been deleted will become visible again.

// Retrieve storage account from connection string.
CloudStorageAccount storageAccount = CloudStorageAccount.Parse(
    CloudConfigurationManager.GetSetting("StorageConnectionString"));

// Create the queue client.
CloudQueueClient queueClient = storageAccount.CreateCloudQueueClient();

// Retrieve a reference to a queue.
CloudQueue queue = queueClient.GetQueueReference("myqueue");

foreach (CloudQueueMessage message in queue.GetMessages(20, TimeSpan.FromMinutes(5)))
{
    // Process all messages in less than 5 minutes, deleting each message after processing.
    queue.DeleteMessage(message);
}

获取队列长度Get the queue length

可以获取队列中消息的估计数。You can get an estimate of the number of messages in a queue. 使用 FetchAttributes 方法可请求队列服务检索队列属性,包括消息计数。The FetchAttributes method asks the Queue service to retrieve the queue attributes, including the message count. ApproximateMessageCount 属性返回 FetchAttributes 方法检索到的最后一个值,而不会调用队列服务。The ApproximateMessageCount property returns the last value retrieved by the FetchAttributes method, without calling the Queue service.

// Retrieve storage account from connection string.
CloudStorageAccount storageAccount = CloudStorageAccount.Parse(
    CloudConfigurationManager.GetSetting("StorageConnectionString"));

// Create the queue client.
CloudQueueClient queueClient = storageAccount.CreateCloudQueueClient();

// Retrieve a reference to a queue.
CloudQueue queue = queueClient.GetQueueReference("myqueue");

// Fetch the queue attributes.
queue.FetchAttributes();

// Retrieve the cached approximate message count.
int? cachedMessageCount = queue.ApproximateMessageCount;

// Display number of messages.
Console.WriteLine("Number of messages in queue: " + cachedMessageCount);

删除队列Delete a queue

若要删除队列及其包含的所有消息,请对队列对象调用 Delete 方法。To delete a queue and all the messages contained in it, call the Delete method on the queue object.

// Retrieve storage account from connection string.
CloudStorageAccount storageAccount = CloudStorageAccount.Parse(
    CloudConfigurationManager.GetSetting("StorageConnectionString"));

// Create the queue client.
CloudQueueClient queueClient = storageAccount.CreateCloudQueueClient();

// Retrieve a reference to a queue.
CloudQueue queue = queueClient.GetQueueReference("myqueue");

// Delete the queue.
queue.Delete();

后续步骤Next steps

现在,了解了有关队列存储的基础知识,可单击下面的链接来了解更复杂的存储任务。Now that you've learned the basics of Queue storage, follow these links to learn about more complex storage tasks.