等待 WebClient.DownloadFileTaskAsync 不工作

await WebClient.DownloadFileTaskAsync not working

我正在尝试使用 WebClient.DownloadFileTaskAsync 下载文件,以便我可以使用下载进度事件处理程序。问题是,即使我在 DownloadFileTaskAsync 上使用 await,它实际上并没有等待任务完成并以 0 字节文件立即退出。我做错了什么?

internal static class Program
{
    private static void Main()
    {
        Download("http://ovh.net/files/1Gb.dat", "test.out");
    }

    private async static void Download(string url, string filePath)
    {
        using (var webClient = new WebClient())
        {
            IWebProxy webProxy = WebRequest.DefaultWebProxy;
            webProxy.Credentials = CredentialCache.DefaultCredentials;
            webClient.Proxy = webProxy;
            webClient.DownloadProgressChanged += (s, e) => Console.Write($"{e.ProgressPercentage}%");
            webClient.DownloadFileCompleted += (s, e) => Console.WriteLine();
            await webClient.DownloadFileTaskAsync(new Uri(url), filePath).ConfigureAwait(false);
        }
    }
}

正如其他人指出的那样,显示的两个方法不是异步的就是不可等待的。

首先,您需要使下载方法可等待:

private async static Task DownloadAsync(string url, string filePath)
{
    using (var webClient = new WebClient())
    {
        IWebProxy webProxy = WebRequest.DefaultWebProxy;
        webProxy.Credentials = CredentialCache.DefaultCredentials;
        webClient.Proxy = webProxy;
        webClient.DownloadProgressChanged += (s, e) => Console.Write($"{e.ProgressPercentage}%");
        webClient.DownloadFileCompleted += (s, e) => Console.WriteLine();
        await webClient.DownloadFileTaskAsync(new Uri(url), filePath).ConfigureAwait(false);
    }
}

然后,您要么等待 Main:

private static void Main()
{
    DownloadAsync("http://ovh.net/files/1Gb.dat", "test.out").Wait();
}

或者,make it asynchronous,也是:

private static async Task Main()
{
    await DownloadAsync("http://ovh.net/files/1Gb.dat", "test.out");
}