

 AWS SDK untuk .NET V3 telah memasuki mode pemeliharaan.

Kami menyarankan Anda bermigrasi ke [AWS SDK untuk .NET V4](https://docs.aws.amazon.com/sdk-for-net/v4/developer-guide/welcome.html). Untuk detail dan informasi tambahan tentang cara bermigrasi, silakan lihat [pengumuman mode pemeliharaan](https://aws.amazon.com/blogs/developer/aws-sdk-for-net-v3-maintenance-mode-announcement/) kami.

Terjemahan disediakan oleh mesin penerjemah. Jika konten terjemahan yang diberikan bertentangan dengan versi bahasa Inggris aslinya, utamakan versi bahasa Inggris.

# Perpesanan menggunakan Amazon SQS
<a name="sqs-apis-intro"></a>

 AWS SDK untuk .NET Mendukung [Amazon Simple Queue Service (Amazon Simple Queue Service](https://docs.aws.amazon.com/AWSSimpleQueueService/latest/SQSDeveloperGuide/)), yang merupakan layanan antrian pesan yang menangani pesan atau alur kerja antar komponen dalam sistem.

Antrian Amazon SQS menyediakan mekanisme yang memungkinkan Anda mengirim, menyimpan, dan menerima pesan antara komponen perangkat lunak seperti layanan mikro, sistem terdistribusi, dan aplikasi tanpa server. Ini memungkinkan Anda untuk memisahkan komponen tersebut dan membebaskan Anda dari kebutuhan untuk merancang dan mengoperasikan sistem pesan Anda sendiri. [Untuk informasi tentang cara kerja antrian dan pesan di Amazon SQS, lihat tutorial Amazon SQS [dan arsitektur Amazon SQS](https://docs.aws.amazon.com/AWSSimpleQueueService/latest/SQSDeveloperGuide/sqs-other-tutorials.html)[Dasar di Panduan Pengembang Layanan Antrian Sederhana Amazon](https://docs.aws.amazon.com/AWSSimpleQueueService/latest/SQSDeveloperGuide/sqs-basic-architecture.html).](https://docs.aws.amazon.com/AWSSimpleQueueService/latest/SQSDeveloperGuide/)

**penting**  
Karena sifat antrian yang terdistribusi, Amazon SQS tidak dapat menjamin bahwa Anda akan menerima pesan dalam urutan yang tepat yang dikirim. Jika Anda perlu mempertahankan urutan pesan, gunakan antrean [Amazon SQS FIFO](https://docs.aws.amazon.com/AWSSimpleQueueService/latest/SQSDeveloperGuide/sqs-fifo-queues.html).

## APIs
<a name="w2aac19c15c25b9"></a>

 AWS SDK untuk .NET Menyediakan APIs untuk klien Amazon SQS. Ini APIs memungkinkan Anda untuk bekerja dengan fitur Amazon SQS seperti antrian dan pesan. Bagian ini berisi sejumlah kecil contoh yang menunjukkan pola yang dapat Anda ikuti saat bekerja dengan ini APIs. Untuk melihat set lengkap APIs, lihat [Referensi AWS SDK untuk .NET API](https://docs.aws.amazon.com/sdkfornet/v3/apidocs/) (dan gulir ke “Amazon.sqs”).

Amazon SQS APIs disediakan oleh [AWSSDK NuGet paket.SQS](https://www.nuget.org/packages/AWSSDK.SQS).

## Prasyarat
<a name="w2aac19c15c25c11"></a>

Sebelum Anda mulai, pastikan Anda telah [mengatur lingkungan dan proyek Anda](net-dg-config.md). Juga tinjau informasi di[Fitur SDK](net-dg-sdk-features.md).

## Topik
<a name="w2aac19c15c25c13"></a>

**Topics**
+ [APIs](#w2aac19c15c25b9)
+ [Prasyarat](#w2aac19c15c25c11)
+ [Topik](#w2aac19c15c25c13)
+ [Membuat antrian](CreateQueue.md)
+ [Memperbarui antrian](UpdateSqsQueue.md)
+ [Menghapus antrian](DeleteSqsQueue.md)
+ [Mengirim pesan](SendMessage.md)
+ [Menerima pesan](ReceiveMessage.md)

# Membuat antrian Amazon SQS
<a name="CreateQueue"></a>

Contoh ini menunjukkan cara menggunakan antrean Amazon SQS AWS SDK untuk .NET untuk membuat antrean Amazon SQS. Aplikasi membuat [antrian huruf mati](https://docs.aws.amazon.com/AWSSimpleQueueService/latest/SQSDeveloperGuide/sqs-dead-letter-queues.html) jika Anda tidak menyediakan ARN untuk satu. Kemudian membuat antrian pesan standar, yang mencakup antrian huruf mati (yang Anda berikan atau yang dibuat).

Jika Anda tidak memberikan argumen baris perintah apa pun, aplikasi hanya menampilkan informasi tentang semua antrian yang ada.

Bagian berikut menyediakan cuplikan dari contoh ini. [Kode lengkap untuk contoh](#CreateQueue-complete-code) ditampilkan setelah itu, dan dapat dibangun dan dijalankan apa adanya.

**Topics**
+ [Tampilkan antrian yang ada](#CreateQueue-show-queues)
+ [Buat antrian](#CreateQueue-create-queue)
+ [Dapatkan ARN antrian](#CreateQueue-get-arn)
+ [Kode lengkap](#CreateQueue-complete-code)
+ [Pertimbangan tambahan](#CreateQueue-additional)

## Tampilkan antrian yang ada
<a name="CreateQueue-show-queues"></a>

Cuplikan berikut menunjukkan daftar antrian yang ada di wilayah klien SQS dan atribut setiap antrian.

Contoh [di akhir topik ini](#CreateQueue-complete-code) menunjukkan cuplikan ini digunakan.

```
    //
    // 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}");
    }
```

## Buat antrian
<a name="CreateQueue-create-queue"></a>

Cuplikan berikut membuat antrian. Cuplikan ini mencakup penggunaan antrian huruf mati, tetapi antrian huruf mati tidak selalu diperlukan untuk antrian Anda.

Contoh [di akhir topik ini](#CreateQueue-complete-code) menunjukkan cuplikan ini digunakan.

```
    //
    // 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;
    }
```

## Dapatkan ARN antrian
<a name="CreateQueue-get-arn"></a>

Cuplikan berikut mendapatkan ARN dari antrian yang diidentifikasi oleh URL antrian yang diberikan.

Contoh [di akhir topik ini](#CreateQueue-complete-code) menunjukkan cuplikan ini digunakan.

```
    //
    // 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;
    }
```

## Kode lengkap
<a name="CreateQueue-complete-code"></a>

Bagian ini menunjukkan referensi yang relevan dan kode lengkap untuk contoh ini.

### Referensi SDK
<a name="w2aac19c15c25c17c25b5b1"></a>

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

Elemen pemrograman:
+ [Namespace Amazon.sqs](https://docs.aws.amazon.com/sdkfornet/v3/apidocs/items/SQS/NSQS.html)

  Kelas [Amazon SQSClient](https://docs.aws.amazon.com/sdkfornet/v3/apidocs/items/SQS/TSQSClient.html)

  Kelas [QueueAttributeName](https://docs.aws.amazon.com/sdkfornet/v3/apidocs/items/SQS/TQueueAttributeName.html)
+ [Namespace Amazon.sqs.Model](https://docs.aws.amazon.com/sdkfornet/v3/apidocs/items/SQS/NSQSModel.html)

  Kelas [CreateQueueRequest](https://docs.aws.amazon.com/sdkfornet/v3/apidocs/items/SQS/TCreateQueueRequest.html)

  Kelas [CreateQueueResponse](https://docs.aws.amazon.com/sdkfornet/v3/apidocs/items/SQS/TCreateQueueResponse.html)

  Kelas [GetQueueAttributesResponse](https://docs.aws.amazon.com/sdkfornet/v3/apidocs/items/SQS/TGetQueueAttributesResponse.html)

  Kelas [ListQueuesResponse](https://docs.aws.amazon.com/sdkfornet/v3/apidocs/items/SQS/TListQueuesResponse.html)

### Kodenya
<a name="w2aac19c15c25c17c25b7b1"></a>

```
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);
    }
  }

}
```

## Pertimbangan tambahan
<a name="CreateQueue-additional"></a>
+ Nama antrian Anda harus terdiri dari karakter alfanumerik, tanda hubung, dan garis bawah.
+ Nama antrian dan antrian peka huruf URLs besar/kecil
+ Jika Anda memerlukan URL antrian tetapi hanya memiliki nama antrian, gunakan salah satu metode. `AmazonSQSClient.GetQueueUrlAsync`
+ Untuk informasi tentang berbagai atribut antrian yang dapat Anda atur, lihat [CreateQueueRequest](https://docs.aws.amazon.com/sdkfornet/v3/apidocs/items/SQS/TCreateQueueRequest.html)di [Referensi AWS SDK untuk .NET API atau [SetQueueAttributes](https://docs.aws.amazon.com/AWSSimpleQueueService/latest/APIReference/API_SetQueueAttributes.html)Referensi](https://docs.aws.amazon.com/sdkfornet/v3/apidocs/) [API Layanan Antrian Sederhana Amazon](https://docs.aws.amazon.com/AWSSimpleQueueService/latest/APIReference/).
+ Contoh ini menentukan polling panjang untuk semua pesan pada antrian yang Anda buat. Hal ini dilakukan dengan menggunakan `ReceiveMessageWaitTimeSeconds` atribut.

  Anda juga dapat menentukan polling panjang selama panggilan ke `ReceiveMessageAsync` metode SQSClient kelas [Amazon](https://docs.aws.amazon.com/sdkfornet/v3/apidocs/items/SQS/TSQSClient.html). Untuk informasi selengkapnya, lihat [Menerima pesan Amazon SQS](ReceiveMessage.md).

  Untuk informasi tentang polling singkat versus polling panjang, lihat Pemungutan suara [pendek dan panjang di Panduan](https://docs.aws.amazon.com/AWSSimpleQueueService/latest/SQSDeveloperGuide/sqs-short-and-long-polling.html) Pengembang Layanan *Antrian Sederhana Amazon*.
+ Antrian surat mati adalah antrian yang dapat ditargetkan oleh antrian (sumber) lain untuk pesan yang tidak berhasil diproses. Untuk informasi selengkapnya, lihat [antrian surat mati Amazon SQS di Panduan Pengembang Layanan Antrian](https://docs.aws.amazon.com/AWSSimpleQueueService/latest/SQSDeveloperGuide/sqs-dead-letter-queues.html) Sederhana Amazon.
+ Anda juga dapat melihat daftar antrian dan hasil contoh ini di konsol [Amazon SQS](https://console.aws.amazon.com/sqs).

# Memperbarui antrian Amazon SQS
<a name="UpdateSqsQueue"></a>

Contoh ini menunjukkan cara menggunakan AWS SDK untuk .NET untuk memperbarui antrian Amazon SQS. Setelah beberapa pemeriksaan, aplikasi memperbarui atribut yang diberikan dengan nilai yang diberikan, dan kemudian menampilkan semua atribut untuk antrian.

Jika hanya URL antrian yang disertakan dalam argumen baris perintah, aplikasi hanya menampilkan semua atribut untuk antrian.

Bagian berikut menyediakan cuplikan dari contoh ini. [Kode lengkap untuk contoh](#UpdateSqsQueue-complete-code) ditampilkan setelah itu, dan dapat dibangun dan dijalankan apa adanya.

**Topics**
+ [Tampilkan atribut antrian](#UpdateSqsQueue-show-attributes)
+ [Validasi nama atribut](#UpdateSqsQueue-validate-attribute)
+ [Perbarui atribut antrian](#UpdateSqsQueue-update-attribute)
+ [Kode lengkap](#UpdateSqsQueue-complete-code)
+ [Pertimbangan tambahan](#UpdateSqsQueue-additional)

## Tampilkan atribut antrian
<a name="UpdateSqsQueue-show-attributes"></a>

Cuplikan berikut menunjukkan atribut antrian yang diidentifikasi oleh URL antrian yang diberikan.

Contoh [di akhir topik ini](#UpdateSqsQueue-complete-code) menunjukkan cuplikan ini digunakan.

```
    //
    // 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}");
    }
```

## Validasi nama atribut
<a name="UpdateSqsQueue-validate-attribute"></a>

Cuplikan berikut memvalidasi nama atribut yang sedang diperbarui.

Contoh [di akhir topik ini](#UpdateSqsQueue-complete-code) menunjukkan cuplikan ini digunakan.

```
    //
    // 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;
    }
```

## Perbarui atribut antrian
<a name="UpdateSqsQueue-update-attribute"></a>

Cuplikan berikut memperbarui atribut antrian yang diidentifikasi oleh URL antrian yang diberikan.

Contoh [di akhir topik ini](#UpdateSqsQueue-complete-code) menunjukkan cuplikan ini digunakan.

```
    //
    // 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}});
    }
```

## Kode lengkap
<a name="UpdateSqsQueue-complete-code"></a>

Bagian ini menunjukkan referensi yang relevan dan kode lengkap untuk contoh ini.

### Referensi SDK
<a name="w2aac19c15c25c19c25b5b1"></a>

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

Elemen pemrograman:
+ [Namespace Amazon.sqs](https://docs.aws.amazon.com/sdkfornet/v3/apidocs/items/SQS/NSQS.html)

  Kelas [Amazon SQSClient](https://docs.aws.amazon.com/sdkfornet/v3/apidocs/items/SQS/TSQSClient.html)

  Kelas [QueueAttributeName](https://docs.aws.amazon.com/sdkfornet/v3/apidocs/items/SQS/TQueueAttributeName.html)
+ [Namespace Amazon.sqs.Model](https://docs.aws.amazon.com/sdkfornet/v3/apidocs/items/SQS/NSQSModel.html)

  Kelas [GetQueueAttributesResponse](https://docs.aws.amazon.com/sdkfornet/v3/apidocs/items/SQS/TGetQueueAttributesResponse.html)

### Kodenya
<a name="w2aac19c15c25c19c25b7b1"></a>

```
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);
    }
  }

}
```

## Pertimbangan tambahan
<a name="UpdateSqsQueue-additional"></a>
+ Untuk memperbarui `RedrivePolicy` atribut, Anda harus mengutip seluruh nilai dan menghindari tanda kutip untuk key/value pasangan, yang sesuai untuk sistem operasi Anda.

  Pada Windows, misalnya, nilainya dibangun dengan cara yang mirip dengan yang berikut ini:

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

# Menghapus antrian Amazon SQS
<a name="DeleteSqsQueue"></a>

Contoh ini menunjukkan cara menggunakan antrean Amazon SQS AWS SDK untuk .NET untuk menghapus. Aplikasi menghapus antrian, menunggu hingga jumlah waktu tertentu untuk antrian hilang, dan kemudian menunjukkan daftar antrian yang tersisa.

Jika Anda tidak memberikan argumen baris perintah apa pun, aplikasi hanya menampilkan daftar antrian yang ada.

Bagian berikut menyediakan cuplikan dari contoh ini. [Kode lengkap untuk contoh](#DeleteSqsQueue-complete-code) ditampilkan setelah itu, dan dapat dibangun dan dijalankan apa adanya.

**Topics**
+ [Hapus antrian](#DeleteSqsQueue-delete-queue)
+ [Tunggu antrian hilang](#DeleteSqsQueue-wait)
+ [Tampilkan daftar antrian yang ada](#DeleteSqsQueue-list-queues)
+ [Kode lengkap](#DeleteSqsQueue-complete-code)
+ [Pertimbangan tambahan](#DeleteSqsQueue-additional)

## Hapus antrian
<a name="DeleteSqsQueue-delete-queue"></a>

Cuplikan berikut menghapus antrian yang diidentifikasi oleh URL antrian yang diberikan.

Contoh [di akhir topik ini](#DeleteSqsQueue-complete-code) menunjukkan cuplikan ini digunakan.

```
    //
    // 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.");
    }
```

## Tunggu antrian hilang
<a name="DeleteSqsQueue-wait"></a>

Cuplikan berikut menunggu proses penghapusan selesai, yang mungkin memakan waktu 60 detik.

Contoh [di akhir topik ini](#DeleteSqsQueue-complete-code) menunjukkan cuplikan ini digunakan.

```
    //
    // 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;
      }
    }
```

## Tampilkan daftar antrian yang ada
<a name="DeleteSqsQueue-list-queues"></a>

Cuplikan berikut menunjukkan daftar antrian yang ada di wilayah klien SQS.

Contoh [di akhir topik ini](#DeleteSqsQueue-complete-code) menunjukkan cuplikan ini digunakan.

```
    //
    // 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}");
    }
```

## Kode lengkap
<a name="DeleteSqsQueue-complete-code"></a>

Bagian ini menunjukkan referensi yang relevan dan kode lengkap untuk contoh ini.

### Referensi SDK
<a name="w2aac19c15c25c21c25b5b1"></a>

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

Elemen pemrograman:
+ [Namespace Amazon.sqs](https://docs.aws.amazon.com/sdkfornet/v3/apidocs/items/SQS/NSQS.html)

  Kelas [Amazon SQSClient](https://docs.aws.amazon.com/sdkfornet/v3/apidocs/items/SQS/TSQSClient.html)
+ [Namespace Amazon.sqs.Model](https://docs.aws.amazon.com/sdkfornet/v3/apidocs/items/SQS/NSQSModel.html)

  Kelas [ListQueuesResponse](https://docs.aws.amazon.com/sdkfornet/v3/apidocs/items/SQS/TListQueuesResponse.html)

### Kodenya
<a name="w2aac19c15c25c21c25b7b1"></a>

```
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}");
    }
  }
}
```

## Pertimbangan tambahan
<a name="DeleteSqsQueue-additional"></a>
+ Panggilan `DeleteQueueAsync` API tidak memeriksa untuk melihat apakah antrian yang Anda hapus digunakan sebagai antrian huruf mati. Prosedur yang lebih canggih dapat memeriksa ini.
+ Anda juga dapat melihat daftar antrian dan hasil contoh ini di konsol [Amazon SQS](https://console.aws.amazon.com/sqs).

# Mengirim pesan Amazon SQS
<a name="SendMessage"></a>

[Contoh ini menunjukkan kepada Anda cara menggunakan untuk mengirim pesan AWS SDK untuk .NET ke antrean Amazon SQS, yang dapat Anda buat [secara terprogram atau dengan menggunakan konsol](CreateQueue.md) Amazon SQS.](https://console.aws.amazon.com/sqs) Aplikasi mengirimkan satu pesan ke antrian dan kemudian sekumpulan pesan. Aplikasi kemudian menunggu input pengguna, yang dapat berupa pesan tambahan untuk dikirim ke antrian atau permintaan untuk keluar dari aplikasi.

Contoh ini dan [contoh selanjutnya tentang menerima pesan](ReceiveMessage.md) dapat digunakan bersama untuk melihat aliran pesan di Amazon SQS.

Bagian berikut menyediakan cuplikan dari contoh ini. [Kode lengkap untuk contoh](#SendMessage-complete-code) ditampilkan setelah itu, dan dapat dibangun dan dijalankan apa adanya.

**Topics**
+ [Kirim pesan](#SendMessage-send-message)
+ [Kirim sejumlah pesan](#SendMessage-send-batch)
+ [Hapus semua pesan dari antrian](#SendMessage-purge-messages)
+ [Kode lengkap](#SendMessage-complete-code)
+ [Pertimbangan tambahan](#SendMessage-additional)

## Kirim pesan
<a name="SendMessage-send-message"></a>

Cuplikan berikut mengirimkan pesan ke antrian yang diidentifikasi oleh URL antrian yang diberikan.

Contoh [di akhir topik ini](#SendMessage-complete-code) menunjukkan cuplikan ini digunakan.

```
    //
    // 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}");
    }
```

## Kirim sejumlah pesan
<a name="SendMessage-send-batch"></a>

Cuplikan berikut mengirimkan sekumpulan pesan ke antrian yang diidentifikasi oleh URL antrian yang diberikan.

Contoh [di akhir topik ini](#SendMessage-complete-code) menunjukkan cuplikan ini digunakan.

```
    //
    // 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.");
    }
```

## Hapus semua pesan dari antrian
<a name="SendMessage-purge-messages"></a>

Cuplikan berikut menghapus semua pesan dari antrian yang diidentifikasi oleh URL antrian yang diberikan. Ini juga dikenal sebagai *membersihkan antrian*.

Contoh [di akhir topik ini](#SendMessage-complete-code) menunjukkan cuplikan ini digunakan.

```
    //
    // 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}");
    }
```

## Kode lengkap
<a name="SendMessage-complete-code"></a>

Bagian ini menunjukkan referensi yang relevan dan kode lengkap untuk contoh ini.

### Referensi SDK
<a name="w2aac19c15c25c23c25b5b1"></a>

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

Elemen pemrograman:
+ [Namespace Amazon.sqs](https://docs.aws.amazon.com/sdkfornet/v3/apidocs/items/SQS/NSQS.html)

  Kelas [Amazon SQSClient](https://docs.aws.amazon.com/sdkfornet/v3/apidocs/items/SQS/TSQSClient.html)
+ [Namespace Amazon.sqs.Model](https://docs.aws.amazon.com/sdkfornet/v3/apidocs/items/SQS/NSQSModel.html)

  Kelas [PurgeQueueResponse](https://docs.aws.amazon.com/sdkfornet/v3/apidocs/items/SQS/TPurgeQueueResponse.html)

  Kelas [SendMessageBatchResponse](https://docs.aws.amazon.com/sdkfornet/v3/apidocs/items/SQS/TSendMessageBatchResponse.html)

  Kelas [SendMessageResponse](https://docs.aws.amazon.com/sdkfornet/v3/apidocs/items/SQS/TSendMessageResponse.html)

  Kelas [SendMessageBatchRequestEntry](https://docs.aws.amazon.com/sdkfornet/v3/apidocs/items/SQS/TSendMessageBatchRequestEntry.html)

  Kelas [SendMessageBatchResultEntry](https://docs.aws.amazon.com/sdkfornet/v3/apidocs/items/SQS/TSendMessageBatchResultEntry.html)

### Kodenya
<a name="w2aac19c15c25c23c25b7b1"></a>

```
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}");
    }
  }
}
```

## Pertimbangan tambahan
<a name="SendMessage-additional"></a>
+ Untuk informasi tentang berbagai batasan pada pesan, termasuk karakter yang diizinkan, lihat [Kuota yang terkait dengan pesan di Panduan](https://docs.aws.amazon.com/AWSSimpleQueueService/latest/SQSDeveloperGuide/sqs-quotas.html#quotas-messages) [Pengembang Layanan Antrian Sederhana Amazon](https://docs.aws.amazon.com/AWSSimpleQueueService/latest/SQSDeveloperGuide/).
+ Pesan tetap dalam antrian sampai dihapus atau antrian dibersihkan. Ketika pesan telah diterima oleh aplikasi, itu tidak akan terlihat dalam antrian meskipun masih ada dalam antrian. Untuk informasi selengkapnya tentang batas waktu visibilitas, lihat batas waktu visibilitas [Amazon SQS](https://docs.aws.amazon.com/AWSSimpleQueueService/latest/SQSDeveloperGuide/AboutVT.html).
+ Selain isi pesan, Anda juga dapat menambahkan atribut ke pesan. Untuk informasi selengkapnya, lihat [Metadata pesan](https://docs.aws.amazon.com/AWSSimpleQueueService/latest/SQSDeveloperGuide/sqs-message-metadata.html).

# Menerima pesan Amazon SQS
<a name="ReceiveMessage"></a>

[Contoh ini menunjukkan cara menggunakan AWS SDK untuk .NET untuk menerima pesan dari antrean Amazon SQS, yang dapat Anda buat [secara terprogram atau menggunakan konsol](CreateQueue.md) Amazon SQS.](https://console.aws.amazon.com/sqs) Aplikasi membaca satu pesan dari antrian, memproses pesan (dalam hal ini, menampilkan badan pesan di konsol), dan kemudian menghapus pesan dari antrian. Aplikasi mengulangi langkah-langkah ini sampai pengguna mengetik tombol pada keyboard.

Contoh ini dan [contoh sebelumnya tentang mengirim pesan](SendMessage.md) dapat digunakan bersama untuk melihat aliran pesan di Amazon SQS.

Bagian berikut menyediakan cuplikan dari contoh ini. [Kode lengkap untuk contoh](#ReceiveMessage-complete-code) ditampilkan setelah itu, dan dapat dibangun dan dijalankan apa adanya.

**Topics**
+ [Menerima pesan](#ReceiveMessage-receive)
+ [Menghapus pesan](#ReceiveMessage-delete)
+ [Kode lengkap](#ReceiveMessage-complete-code)
+ [Pertimbangan tambahan](#ReceiveMessage-additional)

## Menerima pesan
<a name="ReceiveMessage-receive"></a>

Cuplikan berikut menerima pesan dari antrian yang diidentifikasi oleh URL antrian yang diberikan.

Contoh [di akhir topik ini](#ReceiveMessage-complete-code) menunjukkan cuplikan ini digunakan.

```
    //
    // 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.)
      });
    }
```

## Menghapus pesan
<a name="ReceiveMessage-delete"></a>

Cuplikan berikut menghapus pesan dari antrian yang diidentifikasi oleh URL antrian yang diberikan.

Contoh [di akhir topik ini](#ReceiveMessage-complete-code) menunjukkan cuplikan ini digunakan.

```
    //
    // 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);
    }
```

## Kode lengkap
<a name="ReceiveMessage-complete-code"></a>

Bagian ini menunjukkan referensi yang relevan dan kode lengkap untuk contoh ini.

### Referensi SDK
<a name="w2aac19c15c25c25c21b5b1"></a>

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

Elemen pemrograman:
+ [Namespace Amazon.sqs](https://docs.aws.amazon.com/sdkfornet/v3/apidocs/items/SQS/NSQS.html)

  Kelas [Amazon SQSClient](https://docs.aws.amazon.com/sdkfornet/v3/apidocs/items/SQS/TSQSClient.html)
+ [Namespace Amazon.sqs.Model](https://docs.aws.amazon.com/sdkfornet/v3/apidocs/items/SQS/NSQSModel.html)

  Kelas [ReceiveMessageRequest](https://docs.aws.amazon.com/sdkfornet/v3/apidocs/items/SQS/TReceiveMessageRequest.html)

  Kelas [ReceiveMessageResponse](https://docs.aws.amazon.com/sdkfornet/v3/apidocs/items/SQS/TReceiveMessageResponse.html)

### Kodenya
<a name="w2aac19c15c25c25c21b7b1"></a>

```
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);
    }
  }
}
```

## Pertimbangan tambahan
<a name="ReceiveMessage-additional"></a>
+ Untuk menentukan polling panjang, contoh ini menggunakan `WaitTimeSeconds` properti untuk setiap panggilan ke `ReceiveMessageAsync` metode.

  Anda juga dapat menentukan polling panjang untuk semua pesan pada antrian dengan menggunakan `ReceiveMessageWaitTimeSeconds` atribut saat [membuat](CreateQueue.md) atau [memperbarui](UpdateSqsQueue.md) antrian.

  Untuk informasi tentang polling singkat versus polling panjang, lihat Pemungutan suara [pendek dan panjang di Panduan](https://docs.aws.amazon.com/AWSSimpleQueueService/latest/SQSDeveloperGuide/sqs-short-and-long-polling.html) Pengembang Layanan *Antrian Sederhana Amazon*.
+ Selama pemrosesan pesan, Anda dapat menggunakan tanda terima untuk mengubah batas waktu visibilitas pesan. Untuk informasi tentang cara melakukannya, lihat `ChangeMessageVisibilityAsync` metode SQSClient kelas [Amazon](https://docs.aws.amazon.com/sdkfornet/v3/apidocs/items/SQS/TSQSClient.html).
+ Memanggil `DeleteMessageAsync` metode tanpa syarat akan menghapus pesan dari antrian, terlepas dari pengaturan batas waktu visibilitas.