Ler en inglés

Compartir por


WebClient.DownloadDataCompleted Evento

Definición

Se produce cuando se completa una operación de descarga de datos asincrónica.

C#
public event System.Net.DownloadDataCompletedEventHandler? DownloadDataCompleted;
C#
public event System.Net.DownloadDataCompletedEventHandler DownloadDataCompleted;

Tipo de evento

Ejemplos

En el ejemplo de código siguiente se muestra cómo establecer un controlador de eventos para este evento.

C#
// Sample call : DownLoadDataInBackground ("http://www.contoso.com/GameScores.html");
public static void DownloadDataInBackground(string address)
{
    System.Threading.AutoResetEvent waiter = new System.Threading.AutoResetEvent(false);
    WebClient client = new WebClient();
    Uri uri = new Uri(address);

    // Specify that the DownloadDataCallback method gets called
    // when the download completes.
    client.DownloadDataCompleted += new DownloadDataCompletedEventHandler(DownloadDataCallback);
    client.DownloadDataAsync(uri, waiter);

    // Block the main application thread. Real applications
    // can perform other tasks while waiting for the download to complete.
    waiter.WaitOne();
}

En el ejemplo de código siguiente se muestra una implementación de un controlador para este evento.

C#
private static void DownloadDataCallback(Object sender, DownloadDataCompletedEventArgs e)
{
    System.Threading.AutoResetEvent waiter = (System.Threading.AutoResetEvent)e.UserState;

    try
    {
        // If the request was not canceled and did not throw
        // an exception, display the resource.
        if (!e.Cancelled && e.Error == null)
        {
            byte[] data = (byte[])e.Result;
            string textData = System.Text.Encoding.UTF8.GetString(data);

            Console.WriteLine(textData);
        }
    }
    finally
    {
        // Let the main application thread resume.
        waiter.Set();
    }
}

Comentarios

Advertencia

WebRequest, HttpWebRequest, ServicePointy WebClient están obsoletos y no debe usarlos para el nuevo desarrollo. Use HttpClient en su lugar.

Este evento se genera cada vez que se completa una operación de descarga de datos asincrónica. Las descargas de datos asincrónicas se inician llamando a los métodos DownloadDataAsync.

El DownloadDataCompletedEventHandler es el delegado de este evento. La clase DownloadDataCompletedEventArgs proporciona al controlador de eventos datos de eventos.

Para obtener más información sobre cómo controlar eventos, vea Control y generación de eventos.

Se aplica a

Produto Versións
.NET Core 2.0, Core 2.1, Core 2.2, Core 3.0, Core 3.1, 5, 6, 7, 8, 9, 10
.NET Framework 2.0, 3.0, 3.5, 4.0, 4.5, 4.5.1, 4.5.2, 4.6, 4.6.1, 4.6.2, 4.7, 4.7.1, 4.7.2, 4.8, 4.8.1
.NET Standard 2.0, 2.1