我试图编写一个简单的应用程序,从网上下载一个文件。
class Program
{
static void Main(string[] args)
{
WebClient client = new WebClient();
Uri uri = new Uri("http://download.thinkbroadband.com/100MB.zip");
// Specify that the DownloadFileCallback method gets called
// when the download completes.
client.DownloadFileCompleted += new AsyncCompletedEventHandler(DownloadFileCallback2);
// Specify a progress notification handler.
client.DownloadProgressChanged += new DownloadProgressChangedEventHandler(DownloadProgressCallback);
client.DownloadFileAsync(uri, "serverdata.txt");
Console.WriteLine("Download successful.");
}
private static void DownloadProgressCallback(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 static void DownloadFileCallback2(object sender, AsyncCompletedEventArgs e)
{
// Displays the operation identifier, and the transfer progress.
Console.WriteLine("Download complete");
}
}我在这一行中添加了断点:Console.WriteLine("Download complete");,但它从未命中。程序创建空的serverdata.txt文件。我在控制台中没有收到关于从DownloadProgressCallback下载%的任何更新。我做错了什么?
发布于 2014-07-17 11:20:11
我还没有尝试过这种方法,但是您可以尝试使用IsBusy属性:
while(client.IsBusy)
Thread.Sleep(1000);
Console.WriteLine("Download successful.");或者,如果使用的是WebClient.DownloadFileTaskAsync 4.5,则使用.NET方法
client.DownloadFileTaskAsync(uri, "serverdata.txt").Wait();
Console.WriteLine("Download successful.");发布于 2014-07-17 11:40:16
正如其他人所使用的DownloadFileTaskAsync a所示,在等待任务完成时,您的生活会更轻松。您可以异步await结果,也可以调用Wait()来执行阻塞等待。
以下是代码:
private static void DownloadProgressCallback(object sender, DownloadProgressChangedEventArgs e)
{
// Displays the operation identifier, and the transfer progress.
Console.WriteLine("{0} downloaded {1} of {2} bytes. {3} % complete...",
((TaskCompletionSource<object>)e.UserState).Task.AsyncState,
e.BytesReceived,
e.TotalBytesToReceive,
e.ProgressPercentage);
}
static void Main(string[] args)
{
WebClient client = new WebClient();
Uri uri = new Uri("http://download.thinkbroadband.com/100MB.zip");
// Specify a progress notification handler.
client.DownloadProgressChanged += new DownloadProgressChangedEventHandler(DownloadProgressCallback);
var task = client.DownloadFileTaskAsync(uri, "serverdata.txt"); // use Task based API
task.Wait(); // Wait for download to complete, can deadlock in GUI apps
Console.WriteLine("Download complete");
Console.WriteLine("Download successful.");
}Wait()调用可以在基于GUI的应用程序上死锁,但这对您的情况很好。
https://stackoverflow.com/questions/24802046
复制相似问题