

È stata rilasciata la versione 4 (V4) di\! AWS SDK per .NET 

Per informazioni su come apportare modifiche e migrare le applicazioni, consulta l'argomento sulla [migrazione](https://docs.aws.amazon.com/sdk-for-net/v4/developer-guide/net-dg-v4.html).

 [https://docs.aws.amazon.com/sdk-for-net/v4/developer-guide/net-dg-v4.html](https://docs.aws.amazon.com/sdk-for-net/v4/developer-guide/net-dg-v4.html)

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

# 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)
+ [Elimina 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.");
    }
```

## Elimina 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="w2aac19c15c29c23c25b5b1"></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/v4/apidocs/items/SQS/NSQS.html)

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

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

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

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

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

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

### Il codice
<a name="w2aac19c15c29c23c25b7b1"></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).