

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à.

# 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à.