[英]await WebClient.DownloadFileTaskAsync not working
I'm trying to use WebClient.DownloadFileTaskAsync
to download a file so that I can make use of the download progress event handlers.我正在尝试使用
WebClient.DownloadFileTaskAsync
下载文件,以便我可以使用下载进度事件处理程序。 The problem is that even though I'm using await on DownloadFileTaskAsync
, it's not actually waiting for the task to finish and exits instantly with a 0 byte file.问题是,即使我在
DownloadFileTaskAsync
上使用 await ,它实际上并没有等待任务完成并立即以 0 字节文件退出。 What am I doing wrong?我究竟做错了什么?
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);
}
}
}
As others have pointed, The two methods shown are either not asynchronous or not awaitable.正如其他人指出的那样,显示的两种方法要么不是异步的,要么是不可等待的。
First, you need to make your download method awaitable:首先,您需要使您的下载方法可等待:
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);
}
}
Then, you either wait on Main
:然后,您要么等待
Main
:
private static void Main()
{
DownloadAsync("http://ovh.net/files/1Gb.dat", "test.out").Wait();
}
Or, make it asynchronous , too:或者, 也让它异步:
private static async Task Main()
{
await DownloadAsync("http://ovh.net/files/1Gb.dat", "test.out");
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.