

¡Se AWS SDK para .NET ha publicado la versión 4 (V4) del\$1

Para obtener información sobre los cambios más importantes y la migración de sus aplicaciones, consulte el [tema sobre migración](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)

Las traducciones son generadas a través de traducción automática. En caso de conflicto entre la traducción y la version original de inglés, prevalecerá la version en inglés.

# Eliminación de colas de Amazon SQS
<a name="DeleteSqsQueue"></a>

En este ejemplo, se muestra cómo utilizarla AWS SDK para .NET para eliminar una cola de Amazon SQS. La aplicación elimina la cola, espera un periodo de tiempo determinado a que desaparezca y, a continuación, muestra una lista de las colas restantes.

Si no proporciona ningún argumento de línea de comandos, la aplicación simplemente muestra una lista de las colas existentes.

En las siguientes secciones se proporcionan fragmentos de código de este ejemplo. Tras ello, se muestra el [código completo del ejemplo](#DeleteSqsQueue-complete-code), que se puede compilar y ejecutar tal cual.

**Topics**
+ [Eliminación de la cola](#DeleteSqsQueue-delete-queue)
+ [Espera para que la cola desaparezca](#DeleteSqsQueue-wait)
+ [Visualización de una lista de colas existentes](#DeleteSqsQueue-list-queues)
+ [Código completo](#DeleteSqsQueue-complete-code)
+ [Consideraciones adicionales](#DeleteSqsQueue-additional)

## Eliminación de la cola
<a name="DeleteSqsQueue-delete-queue"></a>

El siguiente fragmento de código elimina la cola identificada por la URL de cola especificada.

El ejemplo que aparece [al final de este tema](#DeleteSqsQueue-complete-code) muestra este fragmento de código en 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.");
    }
```

## Espera para que la cola desaparezca
<a name="DeleteSqsQueue-wait"></a>

El siguiente fragmento de código espera a que finalice el proceso de eliminación, que puede tardar 60 segundos.

El ejemplo que aparece [al final de este tema](#DeleteSqsQueue-complete-code) muestra este fragmento de código en 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;
      }
    }
```

## Visualización de una lista de colas existentes
<a name="DeleteSqsQueue-list-queues"></a>

El siguiente fragmento de código muestra una lista de las colas existentes en la región del cliente de SQS.

El ejemplo que aparece [al final de este tema](#DeleteSqsQueue-complete-code) muestra este fragmento de código en 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}");
    }
```

## Código completo
<a name="DeleteSqsQueue-complete-code"></a>

En esta sección se muestran las referencias relevantes y el código completo de este ejemplo.

### Referencias de SDK
<a name="w2aac19c15c29c21c25b5b1"></a>

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

Elementos de programación:
+ Espacio de nombres [Amazon.SQS](https://docs.aws.amazon.com/sdkfornet/v4/apidocs/items/SQS/NSQS.html)

  Clase [Amazon SQSClient](https://docs.aws.amazon.com/sdkfornet/v4/apidocs/items/SQS/TSQSClient.html)
+ Espacio de nombres [Amazon.SQS.Model](https://docs.aws.amazon.com/sdkfornet/v4/apidocs/items/SQS/NSQSModel.html)

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

### El código
<a name="w2aac19c15c29c21c25b7b1"></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}");
    }
  }
}
```

## Consideraciones adicionales
<a name="DeleteSqsQueue-additional"></a>
+ La llamada a la API `DeleteQueueAsync` no comprueba si la cola que se va a eliminar se está usando como cola de mensajes fallidos. Esto podría comprobarse con un procedimiento más elaborado.
+ La lista de colas y los resultados de este ejemplo también se pueden ver en la [consola de Amazon SQS](https://console.aws.amazon.com/sqs).