WebClient.DownloadDataCompleted 事件

定義

發生於異步數據下載作業完成時。

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

事件類型

範例

下列程式代碼範例示範如何設定此事件的事件處理程式。

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();
}

下列程式代碼範例示範此事件的處理程序實作。

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();
    }
}

備註

注意

WebRequestHttpWebRequestServicePointWebClient 已經過時,您不應該將它們用於新的開發。 請改用 HttpClient

每次異步數據下載作業完成時,都會引發此事件。 異步數據下載的啟動方式是呼叫 DownloadDataAsync 方法。

DownloadDataCompletedEventHandler 是這個事件的委派。 DownloadDataCompletedEventArgs 類別會提供事件處理程式與事件數據。

如需如何處理事件的詳細資訊,請參閱 處理和引發事件

適用於

產品 版本
.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