使用WebClient异步下载文件不起作用
本文关键字:文件 不起作用 下载 异步 WebClient 使用 | 更新日期: 2023-09-27 18:08:43
我正在使用c#在VS15中制作控制台应用程序。这是我的下载类:
class DownloadGamefile
{
public void DownloadFile(string address, string location)
{
WebClient client = new WebClient();
Uri Uri = new Uri(address);
client.DownloadFileCompleted += new AsyncCompletedEventHandler(Completed);
client.DownloadProgressChanged += new DownloadProgressChangedEventHandler(DownloadProgress);
client.DownloadFileAsync(Uri, location);
}
private void DownloadProgress(object sender, DownloadProgressChangedEventArgs e)
{
// Displays the operation identifier, and the transfer progress.
Console.WriteLine("{0} downloaded {1} of {2} bytes. {3} % complete...",
(string)e.UserState,
e.BytesReceived,
e.TotalBytesToReceive,
e.ProgressPercentage);
}
private void Completed(object sender, AsyncCompletedEventArgs e)
{
if (e.Cancelled == true)
{
Console.WriteLine("Download has been canceled.");
}
else
{
Console.WriteLine("Download completed!");
}
}
}
下面是我的main:
class Program
{
static void Main(string[] args)
{
DownloadGamefile DGF = new DownloadGamefile();
DGF.DownloadFile("URL", @"C:'Users'LocDaiLe'Desktop'file.file");
}
}
文件出现在正确的文件夹中,但大小为0字节,我的控制台没有显示任何下载进度。
由于Async调用不会阻塞当前线程,我的猜测是DownloadFileAsync (https://msdn.microsoft.com/en-us/library/ms144196(v=vs.110).aspx)立即返回,导致您的DownloadFile也立即返回。这将在文件下载完成之前终止程序执行。
你需要阻塞线程直到文件下载完成。你考虑过使用。net 4.5 (https://msdn.microsoft.com/en-us/library/hh191443.aspx)中的async/await吗?你也可以使用Progress/Completed事件来同步线程,这样在文件完成之前应用程序不会退出。Console.ReadLine()也应该阻塞当前线程,直到按下Enter键。
我扩展了你的代码来支持线程阻塞。这将使主线程在两次检查之间休眠15秒,直到文件完成。我使用关键字"volatile"(https://msdn.microsoft.com/en-us/library/x13ttww7.aspx)来确保总是抓取最新的值。这对于多线程非常重要。_completed = true位于if/else语句的外部,因为我们希望它即使被取消也能退出。如果需要,可以扩展此解决方案来处理取消的下载。class DownloadGamefile
{
private volatile bool _completed;
public void DownloadFile(string address, string location)
{
WebClient client = new WebClient();
Uri Uri = new Uri(address);
_completed = false;
client.DownloadFileCompleted += new AsyncCompletedEventHandler(Completed);
client.DownloadProgressChanged += new DownloadProgressChangedEventHandler(DownloadProgress);
client.DownloadFileAsync(Uri, location);
}
public bool DownloadCompleted { get { return _completed; } }
private void DownloadProgress(object sender, DownloadProgressChangedEventArgs e)
{
// Displays the operation identifier, and the transfer progress.
Console.WriteLine("{0} downloaded {1} of {2} bytes. {3} % complete...",
(string)e.UserState,
e.BytesReceived,
e.TotalBytesToReceive,
e.ProgressPercentage);
}
private void Completed(object sender, AsyncCompletedEventArgs e)
{
if (e.Cancelled == true)
{
Console.WriteLine("Download has been canceled.");
}
else
{
Console.WriteLine("Download completed!");
}
_completed = true;
}
}
class Program
{
static void Main(string[] args)
{
DownloadGamefile DGF = new DownloadGamefile();
DGF.DownloadFile("URL", @"C:'Users'LocDaiLe'Desktop'file.file");
while (!DGF.DownloadCompleted)
Thread.Sleep(1000);
}
}