【发布时间】: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);
}
}
}
【问题讨论】:
-
你不是在等待
Downloadmain 方法。试试Download("url", "path").Wait(); -
您需要将
Main声明为static async Task Main()并在其中声明await Download(...) -
您没有等待任务完成。如果您想在测试时快速(但通常很糟糕)修复,请在
Download()之后添加.Wait(),但如果您是 async-await 的新手,我建议您阅读如何正确执行此操作(网络已满有很好的参考)。
标签: c# .net async-await webclient