

La AWS SDK per .NET V3 è entrata in modalità manutenzione.

[Ti consigliamo di migrare alla V4.AWS SDK per .NET](https://docs.aws.amazon.com/sdk-for-net/v4/developer-guide/welcome.html) Per ulteriori dettagli e informazioni su come eseguire la migrazione, consulta il nostro annuncio sulla modalità di [manutenzione](https://aws.amazon.com/blogs/developer/aws-sdk-for-net-v3-maintenance-mode-announcement/).

Le traduzioni sono generate tramite traduzione automatica. In caso di conflitto tra il contenuto di una traduzione e la versione originale in Inglese, quest'ultima prevarrà.

# Messaggistica tramite Amazon SQS
<a name="sqs-apis-intro"></a>

 AWS SDK per .NET Supporta [Amazon Simple Queue Service (Amazon SQS), un servizio](https://docs.aws.amazon.com/AWSSimpleQueueService/latest/SQSDeveloperGuide/) di accodamento dei messaggi che gestisce i messaggi o i flussi di lavoro tra i componenti di un sistema.

Le code Amazon SQS forniscono un meccanismo che consente di inviare, archiviare e ricevere messaggi tra componenti software come microservizi, sistemi distribuiti e applicazioni serverless. Ciò consente di disaccoppiare tali componenti e ti libera dalla necessità di progettare e gestire il tuo sistema di messaggistica. Per informazioni sul funzionamento delle code e dei messaggi in Amazon SQS, consulta i tutorial di Amazon SQS [e l'[architettura [Amazon SQS](https://docs.aws.amazon.com/AWSSimpleQueueService/latest/SQSDeveloperGuide/sqs-other-tutorials.html) Basic nella](https://docs.aws.amazon.com/AWSSimpleQueueService/latest/SQSDeveloperGuide/) Amazon](https://docs.aws.amazon.com/AWSSimpleQueueService/latest/SQSDeveloperGuide/sqs-basic-architecture.html) Simple Queue Service Developer Guide.

**Importante**  
A causa della natura distribuita delle code, Amazon SQS non può garantire che riceverai i messaggi nell'ordine preciso in cui vengono inviati. Se devi mantenere l'ordine dei messaggi, usa una coda [FIFO di Amazon SQS.](https://docs.aws.amazon.com/AWSSimpleQueueService/latest/SQSDeveloperGuide/sqs-fifo-queues.html)

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

 AWS SDK per .NET Fornisce APIs i client Amazon SQS. Ti APIs consentono di lavorare con funzionalità di Amazon SQS come code e messaggi. Questa sezione contiene un piccolo numero di esempi che mostrano gli schemi che puoi seguire quando lavori con questi. APIs Per visualizzare il set completo di APIs, consulta l'[AWS SDK per .NET API Reference](https://docs.aws.amazon.com/sdkfornet/v3/apidocs/) (e scorri fino a «Amazon.sqs»).

Amazon SQS è fornito dal APIs [AWSSDK NuGet pacchetto.SQS](https://www.nuget.org/packages/AWSSDK.SQS).

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

Prima di iniziare, assicurati di aver [configurato l'ambiente e il progetto.](net-dg-config.md) Consulta anche le informazioni contenute in[Funzionalità dell'SDK](net-dg-sdk-features.md).

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

**Topics**
+ [APIs](#w2aac19c15c25b9)
+ [Prerequisiti](#w2aac19c15c25c11)
+ [Argomenti](#w2aac19c15c25c13)
+ [Creazione di code](CreateQueue.md)
+ [Aggiornamento delle code](UpdateSqsQueue.md)
+ [Eliminazione delle code](DeleteSqsQueue.md)
+ [Invio di messaggi](SendMessage.md)
+ [Ricezione di messaggi](ReceiveMessage.md)

# Creazione di code Amazon SQS
<a name="CreateQueue"></a>

Questo esempio mostra come utilizzare per AWS SDK per .NET creare una coda Amazon SQS. L'applicazione crea una [coda di lettere](https://docs.aws.amazon.com/AWSSimpleQueueService/latest/SQSDeveloperGuide/sqs-dead-letter-queues.html) non scritte se non viene fornito l'ARN corrispondente. Quindi crea una coda di messaggi standard, che include una coda di lettere non scritte (quella che hai fornito o quella che è stata creata).

Se non fornite alcun argomento della riga di comando, l'applicazione mostra semplicemente le informazioni su tutte le code esistenti.

Le sezioni seguenti forniscono frammenti di questo esempio. Successivamente viene mostrato [il codice completo dell'esempio](#CreateQueue-complete-code), che può essere creato ed eseguito così com'è.

**Topics**
+ [Mostra le code esistenti](#CreateQueue-show-queues)
+ [Crea la coda](#CreateQueue-create-queue)
+ [Ottieni l'ARN di una coda](#CreateQueue-get-arn)
+ [Codice completo](#CreateQueue-complete-code)
+ [Ulteriori considerazioni](#CreateQueue-additional)

## Mostra le code esistenti
<a name="CreateQueue-show-queues"></a>

Il seguente frammento mostra un elenco delle code esistenti nella regione del client SQS e gli attributi di ciascuna coda.

L'esempio [alla fine di questo argomento mostra questo frammento](#CreateQueue-complete-code) in uso.

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

## Crea la coda
<a name="CreateQueue-create-queue"></a>

Il seguente frammento crea una coda. Lo snippet include l'uso di una coda di lettere morte, ma una coda di lettere morte non è necessariamente necessaria per le code.

L'esempio alla [fine di questo argomento mostra questo frammento in](#CreateQueue-complete-code) uso.

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

## Ottieni l'ARN di una coda
<a name="CreateQueue-get-arn"></a>

Il seguente frammento ottiene l'ARN della coda identificata dall'URL della coda specificato.

L'esempio [alla fine di questo argomento mostra questo frammento](#CreateQueue-complete-code) in uso.

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

## Codice completo
<a name="CreateQueue-complete-code"></a>

Questa sezione mostra i riferimenti pertinenti e il codice completo per questo esempio.

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

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

Elementi di programmazione:
+ [Spazio dei nomi Amazon.sqs](https://docs.aws.amazon.com/sdkfornet/v3/apidocs/items/SQS/NSQS.html)

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

  Classe [QueueAttributeName](https://docs.aws.amazon.com/sdkfornet/v3/apidocs/items/SQS/TQueueAttributeName.html)
+ [Spazio dei nomi Amazon.SQS.Model](https://docs.aws.amazon.com/sdkfornet/v3/apidocs/items/SQS/NSQSModel.html)

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

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

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

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

### Il codice
<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);
    }
  }

}
```

## Ulteriori considerazioni
<a name="CreateQueue-additional"></a>
+ Il nome della coda deve essere composto da caratteri alfanumerici, trattini e caratteri di sottolineatura.
+ I nomi delle code e la coda fanno distinzione tra maiuscole e minuscole URLs 
+ Se hai bisogno dell'URL della coda ma hai solo il nome della coda, usa uno dei metodi. `AmazonSQSClient.GetQueueUrlAsync`
+ Per informazioni sui vari attributi di coda che puoi impostare, consulta [CreateQueueRequest](https://docs.aws.amazon.com/sdkfornet/v3/apidocs/items/SQS/TCreateQueueRequest.html)l'[AWS SDK per .NET API Reference](https://docs.aws.amazon.com/sdkfornet/v3/apidocs/) o [SetQueueAttributes](https://docs.aws.amazon.com/AWSSimpleQueueService/latest/APIReference/API_SetQueueAttributes.html)il [Amazon Simple Queue Service API](https://docs.aws.amazon.com/AWSSimpleQueueService/latest/APIReference/) Reference.
+ Questo esempio specifica un polling lungo per tutti i messaggi sulla coda che crei. Questa operazione viene eseguita utilizzando l'attributo. `ReceiveMessageWaitTimeSeconds`

  Puoi anche specificare un polling lungo durante una chiamata ai `ReceiveMessageAsync` metodi della SQSClient classe [Amazon](https://docs.aws.amazon.com/sdkfornet/v3/apidocs/items/SQS/TSQSClient.html). Per ulteriori informazioni, consulta [Ricezione di messaggi Amazon SQS](ReceiveMessage.md).

  Per informazioni sul polling breve rispetto al polling lungo, [consulta Short and long polling nella](https://docs.aws.amazon.com/AWSSimpleQueueService/latest/SQSDeveloperGuide/sqs-short-and-long-polling.html) *Amazon Simple Queue* Service Developer Guide.
+ Una coda di lettere morte è quella che altre code (di origine) possono indirizzare per i messaggi che non vengono elaborati correttamente. Per ulteriori informazioni, consulta le [code di lettera morta di Amazon SQS nella Guida](https://docs.aws.amazon.com/AWSSimpleQueueService/latest/SQSDeveloperGuide/sqs-dead-letter-queues.html) per gli sviluppatori di Amazon Simple Queue Service.
+ Puoi anche visualizzare l'elenco delle code e i risultati di questo esempio nella console [Amazon SQS](https://console.aws.amazon.com/sqs).

# Aggiornamento delle code Amazon SQS
<a name="UpdateSqsQueue"></a>

Questo esempio mostra come utilizzare per AWS SDK per .NET aggiornare una coda Amazon SQS. Dopo alcuni controlli, l'applicazione aggiorna l'attributo specificato con il valore dato, quindi mostra tutti gli attributi per la coda.

Se negli argomenti della riga di comando è incluso solo l'URL della coda, l'applicazione mostra semplicemente tutti gli attributi della coda.

Le sezioni seguenti forniscono frammenti di questo esempio. Successivamente viene mostrato [il codice completo dell'esempio](#UpdateSqsQueue-complete-code), che può essere creato ed eseguito così com'è.

**Topics**
+ [Mostra gli attributi della coda](#UpdateSqsQueue-show-attributes)
+ [Convalida il nome dell'attributo](#UpdateSqsQueue-validate-attribute)
+ [Aggiorna l'attributo della coda](#UpdateSqsQueue-update-attribute)
+ [Codice completo](#UpdateSqsQueue-complete-code)
+ [Ulteriori considerazioni](#UpdateSqsQueue-additional)

## Mostra gli attributi della coda
<a name="UpdateSqsQueue-show-attributes"></a>

Il seguente frammento mostra gli attributi della coda identificata dall'URL della coda specificato.

L'esempio [alla fine di questo argomento mostra questo frammento](#UpdateSqsQueue-complete-code) in uso.

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

## Convalida il nome dell'attributo
<a name="UpdateSqsQueue-validate-attribute"></a>

Il seguente frammento di codice convalida il nome dell'attributo da aggiornare.

L'esempio [alla fine di questo argomento mostra questo](#UpdateSqsQueue-complete-code) frammento in uso.

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

## Aggiorna l'attributo della coda
<a name="UpdateSqsQueue-update-attribute"></a>

Il seguente frammento aggiorna un attributo della coda identificato dall'URL della coda specificato.

L'esempio [alla fine di questo argomento mostra questo frammento](#UpdateSqsQueue-complete-code) in uso.

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

## Codice completo
<a name="UpdateSqsQueue-complete-code"></a>

Questa sezione mostra i riferimenti pertinenti e il codice completo per questo esempio.

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

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

Elementi di programmazione:
+ [Spazio dei nomi Amazon.sqs](https://docs.aws.amazon.com/sdkfornet/v3/apidocs/items/SQS/NSQS.html)

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

  Classe [QueueAttributeName](https://docs.aws.amazon.com/sdkfornet/v3/apidocs/items/SQS/TQueueAttributeName.html)
+ [Spazio dei nomi Amazon.SQS.Model](https://docs.aws.amazon.com/sdkfornet/v3/apidocs/items/SQS/NSQSModel.html)

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

### Il codice
<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);
    }
  }

}
```

## Ulteriori considerazioni
<a name="UpdateSqsQueue-additional"></a>
+ Per aggiornare l'`RedrivePolicy`attributo, è necessario citare l'intero valore ed evitare le virgolette per le key/value coppie, a seconda del sistema operativo in uso.

  In Windows, ad esempio, il valore è costruito in modo simile al seguente:

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

# Eliminazione delle code Amazon SQS
<a name="DeleteSqsQueue"></a>

Questo esempio mostra come utilizzare per AWS SDK per .NET eliminare una coda Amazon SQS. L'applicazione elimina la coda, attende fino a un determinato periodo di tempo che la coda scompaia, quindi mostra un elenco delle code rimanenti.

Se non si fornisce alcun argomento della riga di comando, l'applicazione mostra semplicemente un elenco delle code esistenti.

Le sezioni seguenti forniscono frammenti di questo esempio. Successivamente viene mostrato [il codice completo dell'esempio](#DeleteSqsQueue-complete-code), che può essere creato ed eseguito così com'è.

**Topics**
+ [Eliminare la coda](#DeleteSqsQueue-delete-queue)
+ [Attendi che la coda finisca](#DeleteSqsQueue-wait)
+ [Mostra un elenco di code esistenti](#DeleteSqsQueue-list-queues)
+ [Codice completo](#DeleteSqsQueue-complete-code)
+ [Ulteriori considerazioni](#DeleteSqsQueue-additional)

## Eliminare la coda
<a name="DeleteSqsQueue-delete-queue"></a>

Il seguente frammento elimina la coda identificata dall'URL di coda specificato.

L'esempio [alla fine di questo argomento mostra questo frammento](#DeleteSqsQueue-complete-code) in uso.

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

## Attendi che la coda finisca
<a name="DeleteSqsQueue-wait"></a>

Il seguente frammento attende il completamento del processo di eliminazione, che potrebbe richiedere 60 secondi.

L'esempio [alla fine di questo argomento mostra questo](#DeleteSqsQueue-complete-code) frammento in uso.

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

## Mostra un elenco di code esistenti
<a name="DeleteSqsQueue-list-queues"></a>

Il seguente frammento mostra un elenco delle code esistenti nella regione del client SQS.

L'esempio [alla fine di questo argomento mostra questo frammento](#DeleteSqsQueue-complete-code) in uso.

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

## Codice completo
<a name="DeleteSqsQueue-complete-code"></a>

Questa sezione mostra i riferimenti pertinenti e il codice completo per questo esempio.

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

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

Elementi di programmazione:
+ [Spazio dei nomi Amazon.sqs](https://docs.aws.amazon.com/sdkfornet/v3/apidocs/items/SQS/NSQS.html)

  Classe [Amazon SQSClient](https://docs.aws.amazon.com/sdkfornet/v3/apidocs/items/SQS/TSQSClient.html)
+ [Spazio dei nomi Amazon.SQS.Model](https://docs.aws.amazon.com/sdkfornet/v3/apidocs/items/SQS/NSQSModel.html)

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

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

## Ulteriori considerazioni
<a name="DeleteSqsQueue-additional"></a>
+ La chiamata `DeleteQueueAsync` API non verifica se la coda che stai eliminando viene utilizzata come coda di lettere non scritte. Una procedura più sofisticata potrebbe verificarlo.
+ Puoi anche visualizzare l'elenco delle code e i risultati di questo esempio nella console [Amazon SQS](https://console.aws.amazon.com/sqs).

# Invio di messaggi Amazon SQS
<a name="SendMessage"></a>

[Questo esempio mostra come utilizzare per inviare messaggi AWS SDK per .NET a una coda Amazon SQS, che puoi creare a [livello di codice o utilizzando la console](CreateQueue.md) Amazon SQS.](https://console.aws.amazon.com/sqs) L'applicazione invia un singolo messaggio alla coda e poi un batch di messaggi. L'applicazione attende quindi l'input dell'utente, che può essere costituito da messaggi aggiuntivi da inviare alla coda o da una richiesta di uscita dall'applicazione.

Questo esempio e il [prossimo esempio sulla ricezione di messaggi](ReceiveMessage.md) possono essere usati insieme per visualizzare il flusso dei messaggi in Amazon SQS.

Le sezioni seguenti forniscono frammenti di questo esempio. Successivamente viene mostrato [il codice completo dell'esempio](#SendMessage-complete-code), che può essere creato ed eseguito così com'è.

**Topics**
+ [Invio di un messaggio](#SendMessage-send-message)
+ [Inviare un batch di messaggi](#SendMessage-send-batch)
+ [Eliminare tutti i messaggi dalla coda](#SendMessage-purge-messages)
+ [Codice completo](#SendMessage-complete-code)
+ [Ulteriori considerazioni](#SendMessage-additional)

## Invio di un messaggio
<a name="SendMessage-send-message"></a>

Il seguente frammento invia un messaggio alla coda identificata dall'URL della coda specificato.

L'esempio [alla fine di questo argomento mostra questo frammento](#SendMessage-complete-code) in uso.

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

## Inviare un batch di messaggi
<a name="SendMessage-send-batch"></a>

Il seguente frammento invia un batch di messaggi alla coda identificata dall'URL di coda specificato.

L'esempio [alla fine di questo argomento mostra questo frammento](#SendMessage-complete-code) in uso.

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

## Eliminare tutti i messaggi dalla coda
<a name="SendMessage-purge-messages"></a>

Il seguente frammento elimina tutti i messaggi dalla coda identificata dall'URL di coda specificato. *Questa operazione è nota anche come eliminazione della coda.*

L'esempio [alla fine di questo argomento mostra questo](#SendMessage-complete-code) frammento in uso.

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

## Codice completo
<a name="SendMessage-complete-code"></a>

Questa sezione mostra i riferimenti pertinenti e il codice completo per questo esempio.

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

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

Elementi di programmazione:
+ [Spazio dei nomi Amazon.sqs](https://docs.aws.amazon.com/sdkfornet/v3/apidocs/items/SQS/NSQS.html)

  Classe [Amazon SQSClient](https://docs.aws.amazon.com/sdkfornet/v3/apidocs/items/SQS/TSQSClient.html)
+ [Spazio dei nomi Amazon.SQS.Model](https://docs.aws.amazon.com/sdkfornet/v3/apidocs/items/SQS/NSQSModel.html)

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

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

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

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

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

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

## Ulteriori considerazioni
<a name="SendMessage-additional"></a>
+ Per informazioni sulle varie limitazioni sui messaggi, inclusi i caratteri consentiti, consulta [Quote relative ai messaggi](https://docs.aws.amazon.com/AWSSimpleQueueService/latest/SQSDeveloperGuide/sqs-quotas.html#quotas-messages) nella [Amazon Simple Queue Service Developer](https://docs.aws.amazon.com/AWSSimpleQueueService/latest/SQSDeveloperGuide/) Guide.
+ I messaggi rimangono in coda finché non vengono eliminati o la coda non viene eliminata. Quando un messaggio viene ricevuto da un'applicazione, non sarà visibile nella coda anche se esiste ancora nella coda. Per ulteriori informazioni sui timeout di visibilità, consulta [Amazon SQS](https://docs.aws.amazon.com/AWSSimpleQueueService/latest/SQSDeveloperGuide/AboutVT.html) visibility timeout.
+ Oltre al corpo del messaggio, puoi anche aggiungere attributi ai messaggi. Per ulteriori informazioni, consulta [Metadati dei messaggi](https://docs.aws.amazon.com/AWSSimpleQueueService/latest/SQSDeveloperGuide/sqs-message-metadata.html).

# Ricezione di messaggi Amazon SQS
<a name="ReceiveMessage"></a>

[Questo esempio mostra come utilizzare per AWS SDK per .NET ricevere messaggi da una coda Amazon SQS, che puoi creare a [livello di codice o utilizzando la console](CreateQueue.md) Amazon SQS.](https://console.aws.amazon.com/sqs) L'applicazione legge un singolo messaggio dalla coda, elabora il messaggio (in questo caso, visualizza il corpo del messaggio sulla console) e quindi elimina il messaggio dalla coda. L'applicazione ripete questi passaggi finché l'utente non digita un tasto sulla tastiera.

Questo esempio e l'[esempio precedente sull'invio di messaggi](SendMessage.md) possono essere usati insieme per visualizzare il flusso dei messaggi in Amazon SQS.

Le sezioni seguenti forniscono frammenti di questo esempio. Successivamente viene mostrato [il codice completo dell'esempio](#ReceiveMessage-complete-code), che può essere creato ed eseguito così com'è.

**Topics**
+ [Ricevi un messaggio](#ReceiveMessage-receive)
+ [Eliminare un messaggio](#ReceiveMessage-delete)
+ [Codice completo](#ReceiveMessage-complete-code)
+ [Ulteriori considerazioni](#ReceiveMessage-additional)

## Ricevi un messaggio
<a name="ReceiveMessage-receive"></a>

Il seguente frammento riceve un messaggio dalla coda identificata dall'URL di coda specificato.

L'esempio [alla fine di questo argomento mostra questo frammento](#ReceiveMessage-complete-code) in uso.

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

## Eliminare un messaggio
<a name="ReceiveMessage-delete"></a>

Il seguente frammento elimina un messaggio dalla coda identificata dall'URL di coda specificato.

L'esempio [alla fine di questo argomento mostra questo frammento](#ReceiveMessage-complete-code) in uso.

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

## Codice completo
<a name="ReceiveMessage-complete-code"></a>

Questa sezione mostra i riferimenti pertinenti e il codice completo per questo esempio.

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

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

Elementi di programmazione:
+ [Spazio dei nomi Amazon.sqs](https://docs.aws.amazon.com/sdkfornet/v3/apidocs/items/SQS/NSQS.html)

  Classe [Amazon SQSClient](https://docs.aws.amazon.com/sdkfornet/v3/apidocs/items/SQS/TSQSClient.html)
+ [Spazio dei nomi Amazon.SQS.Model](https://docs.aws.amazon.com/sdkfornet/v3/apidocs/items/SQS/NSQSModel.html)

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

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

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

## Ulteriori considerazioni
<a name="ReceiveMessage-additional"></a>
+ Per specificare un polling lungo, in questo esempio viene utilizzata la `WaitTimeSeconds` proprietà per ogni chiamata al `ReceiveMessageAsync` metodo.

  È inoltre possibile specificare un polling lungo per tutti i messaggi in una coda utilizzando l'`ReceiveMessageWaitTimeSeconds`attributo durante la [creazione](CreateQueue.md) o l'[aggiornamento](UpdateSqsQueue.md) della coda.

  Per informazioni sul polling breve rispetto al polling lungo, [consulta Short and long polling nella](https://docs.aws.amazon.com/AWSSimpleQueueService/latest/SQSDeveloperGuide/sqs-short-and-long-polling.html) *Amazon Simple Queue* Service Developer Guide.
+ Durante l'elaborazione dei messaggi, puoi utilizzare la maniglia di ricezione per modificare il timeout di visibilità dei messaggi. Per informazioni su come eseguire questa operazione, consulta i `ChangeMessageVisibilityAsync` metodi della SQSClient classe [Amazon](https://docs.aws.amazon.com/sdkfornet/v3/apidocs/items/SQS/TSQSClient.html).
+ La chiamata al `DeleteMessageAsync` metodo rimuove incondizionatamente il messaggio dalla coda, indipendentemente dall'impostazione del timeout di visibilità.