

的版本 4 (V4) 适用于 .NET 的 Amazon SDK 已经发布！

有关重大更改和迁移应用程序的信息，请参阅[迁移主题](https://docs.amazonaws.cn/sdk-for-net/v4/developer-guide/net-dg-v4.html)。

 [https://docs.amazonaws.cn/sdk-for-net/v4/developer-guide/net-dg-v4.html](https://docs.amazonaws.cn/sdk-for-net/v4/developer-guide/net-dg-v4.html)

本文属于机器翻译版本。若本译文内容与英语原文存在差异，则一律以英文原文为准。

# 使用 Amazon SQS 发送消息
Amazon SQS

 适用于 .NET 的 Amazon SDK 支持[亚马逊简单队列服务 (Amazon SQS](https://docs.amazonaws.cn/AWSSimpleQueueService/latest/SQSDeveloperGuide/)) Simple Queue Service，这是一项消息队列服务，用于处理系统中组件之间的消息或工作流程。

Amazon SQS 队列提供了一种机制，使您能够在微服务、分布式系统和无服务器应用程序等软件组件之间发送、存储和接收消息。这使您能够分离此类组件，无需设计和操作自己的消息传递系统。有关 Amazon SQS 中队列和消息的工作原理的信息，请参阅 [Amazon Simple Queue Service 开发人员指南](https://docs.amazonaws.cn/AWSSimpleQueueService/latest/SQSDeveloperGuide/)中的 [Amazon SQS 教程](https://docs.amazonaws.cn/AWSSimpleQueueService/latest/SQSDeveloperGuide/sqs-other-tutorials.html)和[基本 Amazon SQS 架构](https://docs.amazonaws.cn/AWSSimpleQueueService/latest/SQSDeveloperGuide/sqs-basic-architecture.html)。

**重要**  
由于队列的分布式特性，Amazon SQS 无法保证您以消息发送的准确顺序接收消息。如果您需要保留消息顺序，请使用 [Amazon SQS FIFO 队列](https://docs.amazonaws.cn/AWSSimpleQueueService/latest/SQSDeveloperGuide/sqs-fifo-queues.html)。

## APIs


 APIs 为亚马逊 SQS 客户 适用于 .NET 的 Amazon SDK 提供服务。 APIs 使您可以使用 Amazon SQS 功能，例如队列和消息。本节包含少量示例，向您展示使用这些示例时可以遵循的模式 APIs。要查看全套内容 APIs，请参阅 [适用于 .NET 的 Amazon SDK API 参考](https://docs.amazonaws.cn/sdkfornet/v4/apidocs/)（并滚动至 “Amazon.sqs”）。

亚马逊 SQS APIs 由 [AWSSDK.](https://www.nuget.org/packages/AWSSDK.SQS) NuGet SQS 软件包提供。

## 先决条件


在开始之前，请确保您已经[设置了环境](net-dg-config.md)并[配置了项目](configuring-the-sdk.md)。还要查看[使用 SDK](net-dg-sdk-features.md)中的信息。

## 主题


**Topics**
+ [

## APIs
](#w2aac19c15c29b9)
+ [

## 先决条件
](#w2aac19c15c29c11)
+ [

## 主题
](#w2aac19c15c29c13)
+ [创建队列](CreateQueue.md)
+ [更新队列](UpdateSqsQueue.md)
+ [删除队列](DeleteSqsQueue.md)
+ [发送消息](SendMessage.md)
+ [接收消息](ReceiveMessage.md)

# 创建 Amazon SQS 队列
创建队列

此示例向您展示如何使用创建 Amazon SQS 队列。 适用于 .NET 的 Amazon SDK 如果您不提供[死信队列](https://docs.amazonaws.cn/AWSSimpleQueueService/latest/SQSDeveloperGuide/sqs-dead-letter-queues.html)的 ARN，则应用程序会创建一个死信队列。然后，它会创建一个标准消息队列，其中包括死信队列（您提供的队列或创建的队列）。

如果您不提供任何命令行参数，则应用程序仅显示有关所有现有队列的信息。

以下各节提供了此示例的片段。此后显示了[该示例的完整代码](#CreateQueue-complete-code)，并且可以按原样构建和运行。

**Topics**
+ [

## 显示现有队列
](#CreateQueue-show-queues)
+ [

## 创建队列
](#CreateQueue-create-queue)
+ [

## 获取队列的 ARN
](#CreateQueue-get-arn)
+ [

## 完整代码
](#CreateQueue-complete-code)
+ [

## 其他注意事项
](#CreateQueue-additional)

## 显示现有队列


以下代码片段显示了 SQS 客户端区域中现有队列的列表以及每个队列的属性。

[本主题末尾](#CreateQueue-complete-code)的示例显示了此片段的使用情况。

```
    //
    // Method to show a list of the existing queues
    private static async Task ShowQueues(IAmazonSQS sqsClient)
    {
      ListQueuesResponse responseList = await sqsClient.ListQueuesAsync("");
      Console.WriteLine();
      foreach(string qUrl in responseList.QueueUrls)
      {
        // Get and show all attributes. Could also get a subset.
        await ShowAllAttributes(sqsClient, qUrl);
      }
    }

    //
    // Method to show all attributes of a queue
    private static async Task ShowAllAttributes(IAmazonSQS sqsClient, string qUrl)
    {
      var attributes = new List<string>{ QueueAttributeName.All };
      GetQueueAttributesResponse responseGetAtt =
        await sqsClient.GetQueueAttributesAsync(qUrl, attributes);
      Console.WriteLine($"Queue: {qUrl}");
      foreach(var att in responseGetAtt.Attributes)
        Console.WriteLine($"\t{att.Key}: {att.Value}");
    }
```

## 创建队列


以下代码片段创建队列。该片段包括死信队列的使用，但队列不一定需要死信队列。

[本主题末尾](#CreateQueue-complete-code)的示例显示了此片段的使用情况。

```
    //
    // Method to create a queue. Returns the queue URL.
    private static async Task<string> CreateQueue(
      IAmazonSQS sqsClient, string qName, string deadLetterQueueUrl=null,
      string maxReceiveCount=null, string receiveWaitTime=null)
    {
      var attrs = new Dictionary<string, string>();

      // If a dead-letter queue is given, create a message queue
      if(!string.IsNullOrEmpty(deadLetterQueueUrl))
      {
        attrs.Add(QueueAttributeName.ReceiveMessageWaitTimeSeconds, receiveWaitTime);
        attrs.Add(QueueAttributeName.RedrivePolicy,
          $"{{\"deadLetterTargetArn\":\"{await GetQueueArn(sqsClient, deadLetterQueueUrl)}\"," +
          $"\"maxReceiveCount\":\"{maxReceiveCount}\"}}");
        // Add other attributes for the message queue such as VisibilityTimeout
      }

      // If no dead-letter queue is given, create one of those instead
      //else
      //{
      //  // Add attributes for the dead-letter queue as needed
      //  attrs.Add();
      //}

      // Create the queue
      CreateQueueResponse responseCreate = await sqsClient.CreateQueueAsync(
          new CreateQueueRequest{QueueName = qName, Attributes = attrs});
      return responseCreate.QueueUrl;
    }
```

## 获取队列的 ARN


以下代码片段获取由给定队列 URL 标识的队列的 ARN。

[本主题末尾](#CreateQueue-complete-code)的示例显示了此片段的使用情况。

```
    //
    // Method to get the ARN of a queue
    private static async Task<string> GetQueueArn(IAmazonSQS sqsClient, string qUrl)
    {
      GetQueueAttributesResponse responseGetAtt = await sqsClient.GetQueueAttributesAsync(
        qUrl, new List<string>{QueueAttributeName.QueueArn});
      return responseGetAtt.QueueARN;
    }
```

## 完整代码


本部分显示了本示例的相关参考和完整代码。

### SDK 参考


NuGet 包裹：
+ [AWSSDK.SQS](https://www.nuget.org/packages/AWSSDK.SQS)

编程元素：
+ 命名空间 [Amazon.SQS](https://docs.amazonaws.cn/sdkfornet/v4/apidocs/items/SQS/NSQS.html)

  [Amazon 上](https://docs.amazonaws.cn/sdkfornet/v4/apidocs/items/SQS/TSQSClient.html)课 SQSClient

  班级 [QueueAttributeName](https://docs.amazonaws.cn/sdkfornet/v4/apidocs/items/SQS/TQueueAttributeName.html)
+ 命名空间 [Amazon.SQS.Model](https://docs.amazonaws.cn/sdkfornet/v4/apidocs/items/SQS/NSQSModel.html)

  班级 [CreateQueueRequest](https://docs.amazonaws.cn/sdkfornet/v4/apidocs/items/SQS/TCreateQueueRequest.html)

  班级 [CreateQueueResponse](https://docs.amazonaws.cn/sdkfornet/v4/apidocs/items/SQS/TCreateQueueResponse.html)

  班级 [GetQueueAttributesResponse](https://docs.amazonaws.cn/sdkfornet/v4/apidocs/items/SQS/TGetQueueAttributesResponse.html)

  班级 [ListQueuesResponse](https://docs.amazonaws.cn/sdkfornet/v4/apidocs/items/SQS/TListQueuesResponse.html)

### 代码


```
using System;
using System.Threading.Tasks;
using System.Collections.Generic;
using Amazon.SQS;
using Amazon.SQS.Model;

namespace SQSCreateQueue
{
  // = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = =
  // Class to create a queue
  class Program
  {
    private const string MaxReceiveCount = "10";
    private const string ReceiveMessageWaitTime = "2";
    private const int MaxArgs = 3;

    static async Task Main(string[] args)
    {
      // Parse the command line and show help if necessary
      var parsedArgs = CommandLine.Parse(args);
      if(parsedArgs.Count > MaxArgs)
        CommandLine.ErrorExit(
          "\nToo many command-line arguments.\nRun the command with no arguments to see help.");

      // Create the Amazon SQS client
      var sqsClient = new AmazonSQSClient();

      // In the case of no command-line arguments, just show help and the existing queues
      if(parsedArgs.Count == 0)
      {
        PrintHelp();
        Console.WriteLine("\nNo arguments specified.");
        Console.Write("Do you want to see a list of the existing queues? ((y) or n): ");
        string response = Console.ReadLine();
        if((string.IsNullOrEmpty(response)) || (response.ToLower() == "y"))
          await ShowQueues(sqsClient);
        return;
      }

      // Get the application arguments from the parsed list
      string queueName =
        CommandLine.GetArgument(parsedArgs, null, "-q", "--queue-name");
      string deadLetterQueueUrl =
        CommandLine.GetArgument(parsedArgs, null, "-d", "--dead-letter-queue");
      string maxReceiveCount =
        CommandLine.GetArgument(parsedArgs, MaxReceiveCount, "-m", "--max-receive-count");
      string receiveWaitTime =
        CommandLine.GetArgument(parsedArgs, ReceiveMessageWaitTime, "-w", "--wait-time");

      if(string.IsNullOrEmpty(queueName))
        CommandLine.ErrorExit(
          "\nYou must supply a queue name.\nRun the command with no arguments to see help.");

      // If a dead-letter queue wasn't given, create one
      if(string.IsNullOrEmpty(deadLetterQueueUrl))
      {
        Console.WriteLine("\nNo dead-letter queue was specified. Creating one...");
        deadLetterQueueUrl = await CreateQueue(sqsClient, queueName + "__dlq");
        Console.WriteLine($"Your new dead-letter queue:");
        await ShowAllAttributes(sqsClient, deadLetterQueueUrl);
      }

      // Create the message queue
      string messageQueueUrl = await CreateQueue(
        sqsClient, queueName, deadLetterQueueUrl, maxReceiveCount, receiveWaitTime);
      Console.WriteLine($"Your new message queue:");
      await ShowAllAttributes(sqsClient, messageQueueUrl);
    }


    //
    // Method to show a list of the existing queues
    private static async Task ShowQueues(IAmazonSQS sqsClient)
    {
      ListQueuesResponse responseList = await sqsClient.ListQueuesAsync("");
      Console.WriteLine();
      foreach(string qUrl in responseList.QueueUrls)
      {
        // Get and show all attributes. Could also get a subset.
        await ShowAllAttributes(sqsClient, qUrl);
      }
    }


    //
    // Method to create a queue. Returns the queue URL.
    private static async Task<string> CreateQueue(
      IAmazonSQS sqsClient, string qName, string deadLetterQueueUrl=null,
      string maxReceiveCount=null, string receiveWaitTime=null)
    {
      var attrs = new Dictionary<string, string>();

      // If a dead-letter queue is given, create a message queue
      if(!string.IsNullOrEmpty(deadLetterQueueUrl))
      {
        attrs.Add(QueueAttributeName.ReceiveMessageWaitTimeSeconds, receiveWaitTime);
        attrs.Add(QueueAttributeName.RedrivePolicy,
          $"{{\"deadLetterTargetArn\":\"{await GetQueueArn(sqsClient, deadLetterQueueUrl)}\"," +
          $"\"maxReceiveCount\":\"{maxReceiveCount}\"}}");
        // Add other attributes for the message queue such as VisibilityTimeout
      }

      // If no dead-letter queue is given, create one of those instead
      //else
      //{
      //  // Add attributes for the dead-letter queue as needed
      //  attrs.Add();
      //}

      // Create the queue
      CreateQueueResponse responseCreate = await sqsClient.CreateQueueAsync(
          new CreateQueueRequest{QueueName = qName, Attributes = attrs});
      return responseCreate.QueueUrl;
    }


    //
    // Method to get the ARN of a queue
    private static async Task<string> GetQueueArn(IAmazonSQS sqsClient, string qUrl)
    {
      GetQueueAttributesResponse responseGetAtt = await sqsClient.GetQueueAttributesAsync(
        qUrl, new List<string>{QueueAttributeName.QueueArn});
      return responseGetAtt.QueueARN;
    }


    //
    // Method to show all attributes of a queue
    private static async Task ShowAllAttributes(IAmazonSQS sqsClient, string qUrl)
    {
      var attributes = new List<string>{ QueueAttributeName.All };
      GetQueueAttributesResponse responseGetAtt =
        await sqsClient.GetQueueAttributesAsync(qUrl, attributes);
      Console.WriteLine($"Queue: {qUrl}");
      foreach(var att in responseGetAtt.Attributes)
        Console.WriteLine($"\t{att.Key}: {att.Value}");
    }


    //
    // Command-line help
    private static void PrintHelp()
    {
      Console.WriteLine(
      "\nUsage: SQSCreateQueue -q <queue-name> [-d <dead-letter-queue>]" +
        " [-m <max-receive-count>] [-w <wait-time>]" +
      "\n  -q, --queue-name: The name of the queue you want to create." +
      "\n  -d, --dead-letter-queue: The URL of an existing queue to be used as the dead-letter queue."+
      "\n      If this argument isn't supplied, a new dead-letter queue will be created." +
      "\n  -m, --max-receive-count: The value for maxReceiveCount in the RedrivePolicy of the queue." +
      $"\n      Default is {MaxReceiveCount}." +
      "\n  -w, --wait-time: The value for ReceiveMessageWaitTimeSeconds of the queue for long polling." +
      $"\n      Default is {ReceiveMessageWaitTime}.");
    }
  }


  // = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = =
  // Class that represents a command line on the console or terminal.
  // (This is the same for all examples. When you have seen it once, you can ignore it.)
  static class CommandLine
  {
    //
    // Method to parse a command line of the form: "--key value" or "-k value".
    //
    // Parameters:
    // - args: The command-line arguments passed into the application by the system.
    //
    // Returns:
    // A Dictionary with string Keys and Values.
    //
    // If a key is found without a matching value, Dictionary.Value is set to the key
    //  (including the dashes).
    // If a value is found without a matching key, Dictionary.Key is set to "--NoKeyN",
    //  where "N" represents sequential numbers.
    public static Dictionary<string,string> Parse(string[] args)
    {
      var parsedArgs = new Dictionary<string,string>();
      int i = 0, n = 0;
      while(i < args.Length)
      {
        // If the first argument in this iteration starts with a dash it's an option.
        if(args[i].StartsWith("-"))
        {
          var key = args[i++];
          var value = key;

          // Check to see if there's a value that goes with this option?
          if((i < args.Length) && (!args[i].StartsWith("-"))) value = args[i++];
          parsedArgs.Add(key, value);
        }

        // If the first argument in this iteration doesn't start with a dash, it's a value
        else
        {
          parsedArgs.Add("--NoKey" + n.ToString(), args[i++]);
          n++;
        }
      }

      return parsedArgs;
    }

    //
    // Method to get an argument from the parsed command-line arguments
    //
    // Parameters:
    // - parsedArgs: The Dictionary object returned from the Parse() method (shown above).
    // - defaultValue: The default string to return if the specified key isn't in parsedArgs.
    // - keys: An array of keys to look for in parsedArgs.
    public static string GetArgument(
      Dictionary<string,string> parsedArgs, string defaultReturn, params string[] keys)
    {
      string retval = null;
      foreach(var key in keys)
        if(parsedArgs.TryGetValue(key, out retval)) break;
      return retval ?? defaultReturn;
    }

    //
    // Method to exit the application with an error.
    public static void ErrorExit(string msg, int code=1)
    {
      Console.WriteLine("\nError");
      Console.WriteLine(msg);
      Environment.Exit(code);
    }
  }

}
```

## 其他注意事项

+ 您的队列名称必须由字母数字字符、连字符和下划线组成。
+ 队列名称和队列区 URLs 分大小写
+ 如果您需要队列 URL 但只有队列名称，请使用其中一种 `AmazonSQSClient.GetQueueUrlAsync` 方法。
+ 有关您可以设置的各种队列属性的信息，请参阅 [CreateQueueRequest 适用于 .NET 的 Amazon SDK](https://docs.amazonaws.cn/sdkfornet/v4/apidocs/items/SQS/TCreateQueueRequest.html)[API 参考](https://docs.amazonaws.cn/sdkfornet/v4/apidocs/)或[SetQueueAttributes](https://docs.amazonaws.cn/AWSSimpleQueueService/latest/APIReference/API_SetQueueAttributes.html)《[亚马逊简单队列服务 API 参考](https://docs.amazonaws.cn/AWSSimpleQueueService/latest/APIReference/)》。
+ 此示例指定对您创建的队列中的所有消息进行长轮询。可使用 `ReceiveMessageWaitTimeSeconds` 属性执行此操作。

  您还可以在调用 [Amazon SQSClient](https://docs.amazonaws.cn/sdkfornet/v4/apidocs/items/SQS/TSQSClient.html) 类的`ReceiveMessageAsync`方法期间指定长轮询。有关更多信息，请参阅 [接收 Amazon SQS 消息](ReceiveMessage.md)。

  有关短轮询与长轮询的信息，请参阅《Amazon Simple Queue Service 开发人员指南》**中的[短轮询与长轮询](https://docs.amazonaws.cn/AWSSimpleQueueService/latest/SQSDeveloperGuide/sqs-short-and-long-polling.html)。
+ 其它（源）队列可将未成功处理的消息转到死信队列。有关更多信息，请参阅《Amazon Simple Queue Service 开发人员指南》中的 [Amazon SQS 死信队列](https://docs.amazonaws.cn/AWSSimpleQueueService/latest/SQSDeveloperGuide/sqs-dead-letter-queues.html)。
+ 您还可以在 [Amazon SQS 控制台](https://console.amazonaws.cn/sqs)中查看队列列表和此示例的结果。

# 更新 Amazon SQS 队列
更新队列

此示例向您展示如何使用更新 Amazon SQS 队列。 适用于 .NET 的 Amazon SDK 经过一些检查后，应用程序使用给定值更新给定属性，然后显示队列的所有属性。

如果命令行参数中仅包含队列 URL，则应用程序仅显示队列的所有属性。

以下各节提供了此示例的片段。此后显示了[该示例的完整代码](#UpdateSqsQueue-complete-code)，并且可以按原样构建和运行。

**Topics**
+ [

## 显示队列属性
](#UpdateSqsQueue-show-attributes)
+ [

## 验证属性名称
](#UpdateSqsQueue-validate-attribute)
+ [

## 更新队列属性
](#UpdateSqsQueue-update-attribute)
+ [

## 完整代码
](#UpdateSqsQueue-complete-code)
+ [

## 其他注意事项
](#UpdateSqsQueue-additional)

## 显示队列属性


以下代码片段显示了由给定队列 URL 标识的队列的属性。

[本主题末尾](#UpdateSqsQueue-complete-code)的示例显示了此片段的使用情况。

```
    //
    // Method to show all attributes of a queue
    private static async Task ShowAllAttributes(IAmazonSQS sqsClient, string qUrl)
    {
      GetQueueAttributesResponse responseGetAtt =
        await sqsClient.GetQueueAttributesAsync(qUrl,
          new List<string>{ QueueAttributeName.All });
      Console.WriteLine($"Queue: {qUrl}");
      foreach(var att in responseGetAtt.Attributes)
        Console.WriteLine($"\t{att.Key}: {att.Value}");
    }
```

## 验证属性名称


以下代码片段验证了正在更新的属性的名称。

[本主题末尾](#UpdateSqsQueue-complete-code)的示例显示了此片段的使用情况。

```
    //
    // Method to check the name of the attribute
    private static bool ValidAttribute(string attribute)
    {
      var attOk = false;
      var qAttNameType = typeof(QueueAttributeName);
      List<string> qAttNamefields = new List<string>();
      foreach(var field in qAttNameType.GetFields())
       qAttNamefields.Add(field.Name);
      foreach(var name in qAttNamefields)
        if(attribute == name) { attOk = true; break; }
      return attOk;
    }
```

## 更新队列属性


以下代码片段更新了由给定队列 URL 标识的队列属性。

[本主题末尾](#UpdateSqsQueue-complete-code)的示例显示了此片段的使用情况。

```
    //
    // Method to update a queue attribute
    private static async Task UpdateAttribute(
      IAmazonSQS sqsClient, string qUrl, string attribute, string value)
    {
      await sqsClient.SetQueueAttributesAsync(qUrl,
        new Dictionary<string, string>{{attribute, value}});
    }
```

## 完整代码


本部分显示了本示例的相关参考和完整代码。

### SDK 参考


NuGet 包裹：
+ [AWSSDK.SQS](https://www.nuget.org/packages/AWSSDK.SQS)

编程元素：
+ 命名空间 [Amazon.SQS](https://docs.amazonaws.cn/sdkfornet/v4/apidocs/items/SQS/NSQS.html)

  [Amazon 上](https://docs.amazonaws.cn/sdkfornet/v4/apidocs/items/SQS/TSQSClient.html)课 SQSClient

  班级 [QueueAttributeName](https://docs.amazonaws.cn/sdkfornet/v4/apidocs/items/SQS/TQueueAttributeName.html)
+ 命名空间 [Amazon.SQS.Model](https://docs.amazonaws.cn/sdkfornet/v4/apidocs/items/SQS/NSQSModel.html)

  班级 [GetQueueAttributesResponse](https://docs.amazonaws.cn/sdkfornet/v4/apidocs/items/SQS/TGetQueueAttributesResponse.html)

### 代码


```
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using Amazon.SQS;
using Amazon.SQS.Model;

namespace SQSUpdateQueue
{
  // = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = =
  // Class to update a queue
  class Program
  {
    private const int MaxArgs = 3;
    private const int InvalidArgCount = 2;

    static async Task Main(string[] args)
    {
      // Parse the command line and show help if necessary
      var parsedArgs = CommandLine.Parse(args);
      if(parsedArgs.Count == 0)
      {
        PrintHelp();
        return;
      }
      if((parsedArgs.Count > MaxArgs) || (parsedArgs.Count == InvalidArgCount))
        CommandLine.ErrorExit("\nThe number of command-line arguments is incorrect." +
          "\nRun the command with no arguments to see help.");

      // Get the application arguments from the parsed list
      var qUrl = CommandLine.GetArgument(parsedArgs, null, "-q");
      var attribute = CommandLine.GetArgument(parsedArgs, null, "-a");
      var value = CommandLine.GetArgument(parsedArgs, null, "-v", "--value");

      if(string.IsNullOrEmpty(qUrl))
        CommandLine.ErrorExit("\nYou must supply at least a queue URL." +
          "\nRun the command with no arguments to see help.");

      // Create the Amazon SQS client
      var sqsClient = new AmazonSQSClient();

      // In the case of one command-line argument, just show the attributes for the queue
      if(parsedArgs.Count == 1)
        await ShowAllAttributes(sqsClient, qUrl);

      // Otherwise, attempt to update the given queue attribute with the given value
      else
      {
        // Check to see if the attribute is valid
        if(ValidAttribute(attribute))
        {
          // Perform the update and then show all the attributes of the queue
          await UpdateAttribute(sqsClient, qUrl, attribute, value);
          await ShowAllAttributes(sqsClient, qUrl);
        }
        else
        {
          Console.WriteLine($"\nThe given attribute name, {attribute}, isn't valid.");
        }
      }
    }


    //
    // Method to show all attributes of a queue
    private static async Task ShowAllAttributes(IAmazonSQS sqsClient, string qUrl)
    {
      GetQueueAttributesResponse responseGetAtt =
        await sqsClient.GetQueueAttributesAsync(qUrl,
          new List<string>{ QueueAttributeName.All });
      Console.WriteLine($"Queue: {qUrl}");
      foreach(var att in responseGetAtt.Attributes)
        Console.WriteLine($"\t{att.Key}: {att.Value}");
    }


    //
    // Method to check the name of the attribute
    private static bool ValidAttribute(string attribute)
    {
      var attOk = false;
      var qAttNameType = typeof(QueueAttributeName);
      List<string> qAttNamefields = new List<string>();
      foreach(var field in qAttNameType.GetFields())
       qAttNamefields.Add(field.Name);
      foreach(var name in qAttNamefields)
        if(attribute == name) { attOk = true; break; }
      return attOk;
    }


    //
    // Method to update a queue attribute
    private static async Task UpdateAttribute(
      IAmazonSQS sqsClient, string qUrl, string attribute, string value)
    {
      await sqsClient.SetQueueAttributesAsync(qUrl,
        new Dictionary<string, string>{{attribute, value}});
    }


    //
    // Command-line help
    private static void PrintHelp()
    {
      Console.WriteLine("\nUsage: SQSUpdateQueue -q queue_url [-a attribute -v value]");
      Console.WriteLine("  -q: The URL of the queue you want to update.");
      Console.WriteLine("  -a: The name of the attribute to update.");
      Console.WriteLine("  -v, --value: The value to assign to the attribute.");
    }
  }


  // = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = =
  // Class that represents a command line on the console or terminal.
  // (This is the same for all examples. When you have seen it once, you can ignore it.)
  static class CommandLine
  {
    //
    // Method to parse a command line of the form: "--key value" or "-k value".
    //
    // Parameters:
    // - args: The command-line arguments passed into the application by the system.
    //
    // Returns:
    // A Dictionary with string Keys and Values.
    //
    // If a key is found without a matching value, Dictionary.Value is set to the key
    //  (including the dashes).
    // If a value is found without a matching key, Dictionary.Key is set to "--NoKeyN",
    //  where "N" represents sequential numbers.
    public static Dictionary<string,string> Parse(string[] args)
    {
      var parsedArgs = new Dictionary<string,string>();
      int i = 0, n = 0;
      while(i < args.Length)
      {
        // If the first argument in this iteration starts with a dash it's an option.
        if(args[i].StartsWith("-"))
        {
          var key = args[i++];
          var value = key;

          // Check to see if there's a value that goes with this option?
          if((i < args.Length) && (!args[i].StartsWith("-"))) value = args[i++];
          parsedArgs.Add(key, value);
        }

        // If the first argument in this iteration doesn't start with a dash, it's a value
        else
        {
          parsedArgs.Add("--NoKey" + n.ToString(), args[i++]);
          n++;
        }
      }

      return parsedArgs;
    }

    //
    // Method to get an argument from the parsed command-line arguments
    //
    // Parameters:
    // - parsedArgs: The Dictionary object returned from the Parse() method (shown above).
    // - defaultValue: The default string to return if the specified key isn't in parsedArgs.
    // - keys: An array of keys to look for in parsedArgs.
    public static string GetArgument(
      Dictionary<string,string> parsedArgs, string defaultReturn, params string[] keys)
    {
      string retval = null;
      foreach(var key in keys)
        if(parsedArgs.TryGetValue(key, out retval)) break;
      return retval ?? defaultReturn;
    }

    //
    // Method to exit the application with an error.
    public static void ErrorExit(string msg, int code=1)
    {
      Console.WriteLine("\nError");
      Console.WriteLine(msg);
      Environment.Exit(code);
    }
  }

}
```

## 其他注意事项

+ 要更新该`RedrivePolicy`属性，您必须根据自己的操作系统将整个值加上引号并 key/value 对对的引号进行转义。

  例如，在 Windows 上，该值的构造方式类似于以下内容：

  ```
  "{\"deadLetterTargetArn\":\"DEAD_LETTER-QUEUE-ARN\",\"maxReceiveCount\":\"10\"}"
  ```

# 删除 Amazon SQS 队列
删除队列

此示例向您展示如何使用删除 Amazon SQS 队列。 适用于 .NET 的 Amazon SDK 应用程序删除队列，等到队列消失，然后显示剩余队列的列表。

如果您不提供任何命令行参数，则应用程序仅显示现有队列的列表。

以下各节提供了此示例的片段。此后显示了[该示例的完整代码](#DeleteSqsQueue-complete-code)，并且可以按原样构建和运行。

**Topics**
+ [

## 删除队列
](#DeleteSqsQueue-delete-queue)
+ [

## 等待队列消失
](#DeleteSqsQueue-wait)
+ [

## 显示现有队列的列表
](#DeleteSqsQueue-list-queues)
+ [

## 完整代码
](#DeleteSqsQueue-complete-code)
+ [

## 其他注意事项
](#DeleteSqsQueue-additional)

## 删除队列


以下代码片段删除了由给定队列 URL 标识的队列。

[本主题末尾](#DeleteSqsQueue-complete-code)的示例显示了此片段的使用情况。

```
    //
    // Method to delete an SQS queue
    private static async Task DeleteQueue(IAmazonSQS sqsClient, string qUrl)
    {
      Console.WriteLine($"Deleting queue {qUrl}...");
      await sqsClient.DeleteQueueAsync(qUrl);
      Console.WriteLine($"Queue {qUrl} has been deleted.");
    }
```

## 等待队列消失


以下代码片段等待删除过程完成，这可能需要 60 秒。

[本主题末尾](#DeleteSqsQueue-complete-code)的示例显示了此片段的使用情况。

```
    //
    // Method to wait up to a given number of seconds
    private static async Task Wait(
      IAmazonSQS sqsClient, int numSeconds, string qUrl)
    {
      Console.WriteLine($"Waiting for up to {numSeconds} seconds.");
      Console.WriteLine("Press any key to stop waiting. (Response might be slightly delayed.)");
      for(int i=0; i<numSeconds; i++)
      {
        Console.Write(".");
        Thread.Sleep(1000);
        if(Console.KeyAvailable) break;

        // Check to see if the queue is gone yet
        var found = false;
        ListQueuesResponse responseList = await sqsClient.ListQueuesAsync("");
        foreach(var url in responseList.QueueUrls)
        {
          if(url == qUrl)
          {
            found = true;
            break;
          }
        }
        if(!found) break;
      }
    }
```

## 显示现有队列的列表


以下代码片段显示了 SQS 客户端区域中现有队列的列表。

[本主题末尾](#DeleteSqsQueue-complete-code)的示例显示了此片段的使用情况。

```
    //
    // Method to show a list of the existing queues
    private static async Task ListQueues(IAmazonSQS sqsClient)
    {
      ListQueuesResponse responseList = await sqsClient.ListQueuesAsync("");
      Console.WriteLine("\nList of queues:");
      foreach(var qUrl in responseList.QueueUrls)
        Console.WriteLine($"- {qUrl}");
    }
```

## 完整代码


本部分显示了本示例的相关参考和完整代码。

### SDK 参考


NuGet 包裹：
+ [AWSSDK.SQS](https://www.nuget.org/packages/AWSSDK.SQS)

编程元素：
+ 命名空间 [Amazon.SQS](https://docs.amazonaws.cn/sdkfornet/v4/apidocs/items/SQS/NSQS.html)

  [Amazon 上](https://docs.amazonaws.cn/sdkfornet/v4/apidocs/items/SQS/TSQSClient.html)课 SQSClient
+ 命名空间 [Amazon.SQS.Model](https://docs.amazonaws.cn/sdkfornet/v4/apidocs/items/SQS/NSQSModel.html)

  班级 [ListQueuesResponse](https://docs.amazonaws.cn/sdkfornet/v4/apidocs/items/SQS/TListQueuesResponse.html)

### 代码


```
using System;
using System.Threading;
using System.Threading.Tasks;
using Amazon.SQS;
using Amazon.SQS.Model;

namespace SQSDeleteQueue
{
  // = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = =
  // Class to update a queue
  class Program
  {
    private const int TimeToWait = 60;

    static async Task Main(string[] args)
    {
      // Create the Amazon SQS client
      var sqsClient = new AmazonSQSClient();

      // If no command-line arguments, just show a list of the queues
      if(args.Length == 0)
      {
        Console.WriteLine("\nUsage: SQSCreateQueue queue_url");
        Console.WriteLine("   queue_url - The URL of the queue you want to delete.");
        Console.WriteLine("\nNo arguments specified.");
        Console.Write("Do you want to see a list of the existing queues? ((y) or n): ");
        var response = Console.ReadLine();
        if((string.IsNullOrEmpty(response)) || (response.ToLower() == "y"))
          await ListQueues(sqsClient);
        return;
      }

      // If given a queue URL, delete that queue
      if(args[0].StartsWith("https://sqs."))
      {
        // Delete the queue
        await DeleteQueue(sqsClient, args[0]);
        // Wait for a little while because it takes a while for the queue to disappear
        await Wait(sqsClient, TimeToWait, args[0]);
        // Show a list of the remaining queues
        await ListQueues(sqsClient);
      }
      else
      {
        Console.WriteLine("The command-line argument isn't a queue URL:");
        Console.WriteLine($"{args[0]}");
      }
    }


    //
    // Method to delete an SQS queue
    private static async Task DeleteQueue(IAmazonSQS sqsClient, string qUrl)
    {
      Console.WriteLine($"Deleting queue {qUrl}...");
      await sqsClient.DeleteQueueAsync(qUrl);
      Console.WriteLine($"Queue {qUrl} has been deleted.");
    }


    //
    // Method to wait up to a given number of seconds
    private static async Task Wait(
      IAmazonSQS sqsClient, int numSeconds, string qUrl)
    {
      Console.WriteLine($"Waiting for up to {numSeconds} seconds.");
      Console.WriteLine("Press any key to stop waiting. (Response might be slightly delayed.)");
      for(int i=0; i<numSeconds; i++)
      {
        Console.Write(".");
        Thread.Sleep(1000);
        if(Console.KeyAvailable) break;

        // Check to see if the queue is gone yet
        var found = false;
        ListQueuesResponse responseList = await sqsClient.ListQueuesAsync("");
        foreach(var url in responseList.QueueUrls)
        {
          if(url == qUrl)
          {
            found = true;
            break;
          }
        }
        if(!found) break;
      }
    }


    //
    // Method to show a list of the existing queues
    private static async Task ListQueues(IAmazonSQS sqsClient)
    {
      ListQueuesResponse responseList = await sqsClient.ListQueuesAsync("");
      Console.WriteLine("\nList of queues:");
      foreach(var qUrl in responseList.QueueUrls)
        Console.WriteLine($"- {qUrl}");
    }
  }
}
```

## 其他注意事项

+ `DeleteQueueAsync` API 调用不会检查您要删除的队列是否被用作死信队列。可以用更复杂的程序来检查这一点。
+ 您还可以在 [Amazon SQS 控制台](https://console.amazonaws.cn/sqs)中查看队列列表和此示例的结果。

# 发送 Amazon SMS 消息
发送消息

[此示例向您展示如何使用向 Amazon SQS 队列发送消息，您可以通过[编程方式](CreateQueue.md)或使用 Amazon SQS 控制台创建该队列。 适用于 .NET 的 Amazon SDK](https://console.amazonaws.cn/sqs)应用程序向队列发送一条消息，然后发送一批消息。然后，应用程序等待用户输入，这些输入可以是要发送到队列的额外消息或退出应用程序的请求。

此示例和[下一个有关接收消息的示例](ReceiveMessage.md)可以一起使用，以查看 Amazon SQS 中的消息流。

以下各节提供了此示例的片段。此后显示了[该示例的完整代码](#SendMessage-complete-code)，并且可以按原样构建和运行。

**Topics**
+ [

## 发送消息
](#SendMessage-send-message)
+ [

## 发送一批消息
](#SendMessage-send-batch)
+ [

## 从队列中删除所有消息
](#SendMessage-purge-messages)
+ [

## 完整代码
](#SendMessage-complete-code)
+ [

## 其他注意事项
](#SendMessage-additional)

## 发送消息


以下代码片段将消息发送到由给定队列 URL 标识的队列。

[本主题末尾](#SendMessage-complete-code)的示例显示了此片段的使用情况。

```
    //
    // Method to put a message on a queue
    // Could be expanded to include message attributes, etc., in a SendMessageRequest
    private static async Task SendMessage(
      IAmazonSQS sqsClient, string qUrl, string messageBody)
    {
      SendMessageResponse responseSendMsg =
        await sqsClient.SendMessageAsync(qUrl, messageBody);
      Console.WriteLine($"Message added to queue\n  {qUrl}");
      Console.WriteLine($"HttpStatusCode: {responseSendMsg.HttpStatusCode}");
    }
```

## 发送一批消息


以下代码片段向由给定队列 URL 标识的队列发送一批消息。

[本主题末尾](#SendMessage-complete-code)的示例显示了此片段的使用情况。

```
    //
    // Method to put a batch of messages on a queue
    // Could be expanded to include message attributes, etc.,
    // in the SendMessageBatchRequestEntry objects
    private static async Task SendMessageBatch(
      IAmazonSQS sqsClient, string qUrl, List<SendMessageBatchRequestEntry> messages)
    {
      Console.WriteLine($"\nSending a batch of messages to queue\n  {qUrl}");
      SendMessageBatchResponse responseSendBatch =
        await sqsClient.SendMessageBatchAsync(qUrl, messages);
      // Could test responseSendBatch.Failed here
      foreach(SendMessageBatchResultEntry entry in responseSendBatch.Successful)
        Console.WriteLine($"Message {entry.Id} successfully queued.");
    }
```

## 从队列中删除所有消息


以下代码片段删除了来自由给定队列 URL 标识的队列的所有消息。这也称为*清除队列*。

[本主题末尾](#SendMessage-complete-code)的示例显示了此片段的使用情况。

```
    //
    // Method to delete all messages from the queue
    private static async Task DeleteAllMessages(IAmazonSQS sqsClient, string qUrl)
    {
      Console.WriteLine($"\nPurging messages from queue\n  {qUrl}...");
      PurgeQueueResponse responsePurge = await sqsClient.PurgeQueueAsync(qUrl);
      Console.WriteLine($"HttpStatusCode: {responsePurge.HttpStatusCode}");
    }
```

## 完整代码


本部分显示了本示例的相关参考和完整代码。

### SDK 参考


NuGet 包裹：
+ [AWSSDK.SQS](https://www.nuget.org/packages/AWSSDK.SQS)

编程元素：
+ 命名空间 [Amazon.SQS](https://docs.amazonaws.cn/sdkfornet/v4/apidocs/items/SQS/NSQS.html)

  [Amazon 上](https://docs.amazonaws.cn/sdkfornet/v4/apidocs/items/SQS/TSQSClient.html)课 SQSClient
+ 命名空间 [Amazon.SQS.Model](https://docs.amazonaws.cn/sdkfornet/v4/apidocs/items/SQS/NSQSModel.html)

  班级 [PurgeQueueResponse](https://docs.amazonaws.cn/sdkfornet/v4/apidocs/items/SQS/TPurgeQueueResponse.html)

  班级 [SendMessageBatchResponse](https://docs.amazonaws.cn/sdkfornet/v4/apidocs/items/SQS/TSendMessageBatchResponse.html)

  班级 [SendMessageResponse](https://docs.amazonaws.cn/sdkfornet/v4/apidocs/items/SQS/TSendMessageResponse.html)

  班级 [SendMessageBatchRequestEntry](https://docs.amazonaws.cn/sdkfornet/v4/apidocs/items/SQS/TSendMessageBatchRequestEntry.html)

  班级 [SendMessageBatchResultEntry](https://docs.amazonaws.cn/sdkfornet/v4/apidocs/items/SQS/TSendMessageBatchResultEntry.html)

### 代码


```
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using Amazon.SQS;
using Amazon.SQS.Model;

namespace SQSSendMessages
{
  // = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = =
  // Class to send messages to a queue
  class Program
  {
    // Some example messages to send to the queue
    private const string JsonMessage = "{\"product\":[{\"name\":\"Product A\",\"price\": \"32\"},{\"name\": \"Product B\",\"price\": \"27\"}]}";
    private const string XmlMessage = "<products><product name=\"Product A\" price=\"32\" /><product name=\"Product B\" price=\"27\" /></products>";
    private const string CustomMessage = "||product|Product A|32||product|Product B|27||";
    private const string TextMessage = "Just a plain text message.";

    static async Task Main(string[] args)
    {
      // Do some checks on the command-line
      if(args.Length == 0)
      {
        Console.WriteLine("\nUsage: SQSSendMessages queue_url");
        Console.WriteLine("   queue_url - The URL of an existing SQS queue.");
        return;
      }
      if(!args[0].StartsWith("https://sqs."))
      {
        Console.WriteLine("\nThe command-line argument isn't a queue URL:");
        Console.WriteLine($"{args[0]}");
        return;
      }

      // Create the Amazon SQS client
      var sqsClient = new AmazonSQSClient();

      // (could verify that the queue exists)
      // Send some example messages to the given queue
      // A single message
      await SendMessage(sqsClient, args[0], JsonMessage);

      // A batch of messages
      var batchMessages = new List<SendMessageBatchRequestEntry>{
        new SendMessageBatchRequestEntry("xmlMsg", XmlMessage),
        new SendMessageBatchRequestEntry("customeMsg", CustomMessage),
        new SendMessageBatchRequestEntry("textMsg", TextMessage)};
      await SendMessageBatch(sqsClient, args[0], batchMessages);

      // Let the user send their own messages or quit
      await InteractWithUser(sqsClient, args[0]);

      // Delete all messages that are still in the queue
      await DeleteAllMessages(sqsClient, args[0]);
    }


    //
    // Method to put a message on a queue
    // Could be expanded to include message attributes, etc., in a SendMessageRequest
    private static async Task SendMessage(
      IAmazonSQS sqsClient, string qUrl, string messageBody)
    {
      SendMessageResponse responseSendMsg =
        await sqsClient.SendMessageAsync(qUrl, messageBody);
      Console.WriteLine($"Message added to queue\n  {qUrl}");
      Console.WriteLine($"HttpStatusCode: {responseSendMsg.HttpStatusCode}");
    }


    //
    // Method to put a batch of messages on a queue
    // Could be expanded to include message attributes, etc.,
    // in the SendMessageBatchRequestEntry objects
    private static async Task SendMessageBatch(
      IAmazonSQS sqsClient, string qUrl, List<SendMessageBatchRequestEntry> messages)
    {
      Console.WriteLine($"\nSending a batch of messages to queue\n  {qUrl}");
      SendMessageBatchResponse responseSendBatch =
        await sqsClient.SendMessageBatchAsync(qUrl, messages);
      // Could test responseSendBatch.Failed here
      foreach(SendMessageBatchResultEntry entry in responseSendBatch.Successful)
        Console.WriteLine($"Message {entry.Id} successfully queued.");
    }


    //
    // Method to get input from the user
    // They can provide messages to put in the queue or exit the application
    private static async Task InteractWithUser(IAmazonSQS sqsClient, string qUrl)
    {
      string response;
      while (true)
      {
        // Get the user's input
        Console.WriteLine("\nType a message for the queue or \"exit\" to quit:");
        response = Console.ReadLine();
        if(response.ToLower() == "exit") break;

        // Put the user's message in the queue
        await SendMessage(sqsClient, qUrl, response);
      }
    }


    //
    // Method to delete all messages from the queue
    private static async Task DeleteAllMessages(IAmazonSQS sqsClient, string qUrl)
    {
      Console.WriteLine($"\nPurging messages from queue\n  {qUrl}...");
      PurgeQueueResponse responsePurge = await sqsClient.PurgeQueueAsync(qUrl);
      Console.WriteLine($"HttpStatusCode: {responsePurge.HttpStatusCode}");
    }
  }
}
```

## 其他注意事项

+ 有关消息的各种限制（包括允许的字符）的信息，请参阅 [Amazon Simple Queue Service 开发人员指南](https://docs.amazonaws.cn/AWSSimpleQueueService/latest/SQSDeveloperGuide/)中[与消息相关的配额](https://docs.amazonaws.cn/AWSSimpleQueueService/latest/SQSDeveloperGuide/sqs-quotas.html#quotas-messages)部分。
+ 消息会一直保留在队列中，直到被删除或队列被清除。当应用程序收到一条消息时，即使它仍然存在于队列中，它也不会出现在队列中。有关可见性超时的更多信息，请参阅 [Amazon SQS 可见性超时](https://docs.amazonaws.cn/AWSSimpleQueueService/latest/SQSDeveloperGuide/AboutVT.html)。
+ 除了消息正文外，您还可以为消息添加属性。有关更多信息，请参阅[消息元数据](https://docs.amazonaws.cn/AWSSimpleQueueService/latest/SQSDeveloperGuide/sqs-message-metadata.html)。

# 接收 Amazon SQS 消息
接收消息

[此示例向您展示如何使用接收 适用于 .NET 的 Amazon SDK 来自 Amazon SQS 队列的消息，您可以通过[编程方式](CreateQueue.md)或使用 Amazon SQS 控制台创建该队列。](https://console.amazonaws.cn/sqs)应用程序从队列中读取一条消息，处理该消息（在本例中，在控制台上显示消息正文），然后从队列中删除该消息。应用程序会重复这些步骤，直到用户在键盘上键入一个键。

此示例和[前面有关接收消息的示例](SendMessage.md)可以一起使用，以查看 Amazon SQS 中的消息流。

以下各节提供了此示例的片段。此后显示了[该示例的完整代码](#ReceiveMessage-complete-code)，并且可以按原样构建和运行。

**Topics**
+ [

## 接收消息
](#ReceiveMessage-receive)
+ [

## 删除消息
](#ReceiveMessage-delete)
+ [

## 完整代码
](#ReceiveMessage-complete-code)
+ [

## 其他注意事项
](#ReceiveMessage-additional)

## 接收消息


以下代码片段从由给定队列 URL 标识的队列接收消息。

[本主题末尾](#ReceiveMessage-complete-code)的示例显示了此片段的使用情况。

```
    //
    // Method to read a message from the given queue
    // In this example, it gets one message at a time
    private static async Task<ReceiveMessageResponse> GetMessage(
      IAmazonSQS sqsClient, string qUrl, int waitTime=0)
    {
      return await sqsClient.ReceiveMessageAsync(new ReceiveMessageRequest{
        QueueUrl=qUrl,
        MaxNumberOfMessages=MaxMessages,
        WaitTimeSeconds=waitTime
        // (Could also request attributes, set visibility timeout, etc.)
      });
    }
```

## 删除消息


以下代码片段删除了来自由给定队列 URL 标识的队列的消息。

[本主题末尾](#ReceiveMessage-complete-code)的示例显示了此片段的使用情况。

```
    //
    // Method to delete a message from a queue
    private static async Task DeleteMessage(
      IAmazonSQS sqsClient, Message message, string qUrl)
    {
      Console.WriteLine($"\nDeleting message {message.MessageId} from queue...");
      await sqsClient.DeleteMessageAsync(qUrl, message.ReceiptHandle);
    }
```

## 完整代码


本部分显示了本示例的相关参考和完整代码。

### SDK 参考


NuGet 包裹：
+ [AWSSDK.SQS](https://www.nuget.org/packages/AWSSDK.SQS)

编程元素：
+ 命名空间 [Amazon.SQS](https://docs.amazonaws.cn/sdkfornet/v4/apidocs/items/SQS/NSQS.html)

  [Amazon 上](https://docs.amazonaws.cn/sdkfornet/v4/apidocs/items/SQS/TSQSClient.html)课 SQSClient
+ 命名空间 [Amazon.SQS.Model](https://docs.amazonaws.cn/sdkfornet/v4/apidocs/items/SQS/NSQSModel.html)

  班级 [ReceiveMessageRequest](https://docs.amazonaws.cn/sdkfornet/v4/apidocs/items/SQS/TReceiveMessageRequest.html)

  班级 [ReceiveMessageResponse](https://docs.amazonaws.cn/sdkfornet/v4/apidocs/items/SQS/TReceiveMessageResponse.html)

### 代码


```
using System;
using System.Threading.Tasks;
using Amazon.SQS;
using Amazon.SQS.Model;

namespace SQSReceiveMessages
{
  class Program
  {
    private const int MaxMessages = 1;
    private const int WaitTime = 2;
    static async Task Main(string[] args)
    {
      // Do some checks on the command-line
      if(args.Length == 0)
      {
        Console.WriteLine("\nUsage: SQSReceiveMessages queue_url");
        Console.WriteLine("   queue_url - The URL of an existing SQS queue.");
        return;
      }
      if(!args[0].StartsWith("https://sqs."))
      {
        Console.WriteLine("\nThe command-line argument isn't a queue URL:");
        Console.WriteLine($"{args[0]}");
        return;
      }

      // Create the Amazon SQS client
      var sqsClient = new AmazonSQSClient();

      // (could verify that the queue exists)
      // Read messages from the queue and perform appropriate actions
      Console.WriteLine($"Reading messages from queue\n  {args[0]}");
      Console.WriteLine("Press any key to stop. (Response might be slightly delayed.)");
      do
      {
        var msg = await GetMessage(sqsClient, args[0], WaitTime);
        if(msg.Messages.Count != 0)
        {
          if(ProcessMessage(msg.Messages[0]))
            await DeleteMessage(sqsClient, msg.Messages[0], args[0]);
        }
      } while(!Console.KeyAvailable);
    }


    //
    // Method to read a message from the given queue
    // In this example, it gets one message at a time
    private static async Task<ReceiveMessageResponse> GetMessage(
      IAmazonSQS sqsClient, string qUrl, int waitTime=0)
    {
      return await sqsClient.ReceiveMessageAsync(new ReceiveMessageRequest{
        QueueUrl=qUrl,
        MaxNumberOfMessages=MaxMessages,
        WaitTimeSeconds=waitTime
        // (Could also request attributes, set visibility timeout, etc.)
      });
    }


    //
    // Method to process a message
    // In this example, it simply prints the message
    private static bool ProcessMessage(Message message)
    {
      Console.WriteLine($"\nMessage body of {message.MessageId}:");
      Console.WriteLine($"{message.Body}");
      return true;
    }


    //
    // Method to delete a message from a queue
    private static async Task DeleteMessage(
      IAmazonSQS sqsClient, Message message, string qUrl)
    {
      Console.WriteLine($"\nDeleting message {message.MessageId} from queue...");
      await sqsClient.DeleteMessageAsync(qUrl, message.ReceiptHandle);
    }
  }
}
```

## 其他注意事项

+ 为了指定长轮询，此示例在每次调用 `ReceiveMessageAsync` 方法时都使用该 `WaitTimeSeconds` 属性。

  您还可以在[创建](CreateQueue.md)或[更新](UpdateSqsQueue.md)队列时使用 `ReceiveMessageWaitTimeSeconds` 属性为队列中的所有消息指定长轮询。

  有关短轮询与长轮询的信息，请参阅《Amazon Simple Queue Service 开发人员指南》**中的[短轮询与长轮询](https://docs.amazonaws.cn/AWSSimpleQueueService/latest/SQSDeveloperGuide/sqs-short-and-long-polling.html)。
+ 在消息处理过程中，您可以使用接收句柄来更改消息可见性超时。有关如何执行此操作的信息，请参阅 [Amazon SQSClient](https://docs.amazonaws.cn/sdkfornet/v4/apidocs/items/SQS/TSQSClient.html) 类`ChangeMessageVisibilityAsync`的方法。
+ 调用 `DeleteMessageAsync` 方法将无条件地从队列中删除消息，而无论可见性超时设置如何。