【问题标题】:await WebClient.DownloadFileTaskAsync not working等待 WebClient.DownloadFileTaskAsync 不起作用
【发布时间】:2020-02-27 10:22:59
【问题描述】:

我正在尝试使用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);
        }
    }
}

【问题讨论】:

  • 你不是在等待 Download main 方法。试试Download("url", "path").Wait();
  • 您需要将Main 声明为static async Task Main() 并在其中声明await Download(...)
  • 您没有等待任务完成。如果您想在测试时快速(但通常很糟糕)修复,请在 Download() 之后添加 .Wait(),但如果您是 async-await 的新手,我建议您阅读如何正确执行此操作(网络已满有很好的参考)。

标签: c# .net async-await webclient


【解决方案1】:

正如其他人所指出的,显示的两种方法要么不是异步的,要么不是可等待的。

首先,你需要让你的下载方法可以等待:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-12-15
    • 2017-07-17
    • 1970-01-01
    • 2023-04-07
    • 2018-08-05
    相关资源
    最近更新 更多