【发布时间】:2011-08-09 07:08:07
【问题描述】:
很难找到使用 webclient 类异步方法下载多个文件但一次下载一个文件的代码示例。
如何启动异步下载,但要等到第一个完成后再等到第二个,等等。基本上是一个问题。
(注意我不想使用同步方法,因为异步方法增加了功能。)
下面的代码会立即开始我的所有下载。 (进度条到处都是)
private void downloadFile(string url)
{
WebClient client = new WebClient();
client.DownloadProgressChanged += new DownloadProgressChangedEventHandler(client_DownloadProgressChanged);
client.DownloadFileCompleted += new AsyncCompletedEventHandler(client_DownloadFileCompleted);
// Starts the download
btnGetDownload.Text = "Downloading...";
btnGetDownload.Enabled = false;
progressBar1.Visible = true;
lblFileName.Text = url;
lblFileName.Visible = true;
string FileName = url.Substring(url.LastIndexOf("/") + 1,
(url.Length - url.LastIndexOf("/") - 1));
client.DownloadFileAsync(new Uri(url), "C:\\Test4\\" + FileName);
}
void client_DownloadFileCompleted(object sender, AsyncCompletedEventArgs e)
{
}
void client_DownloadProgressChanged(object sender, DownloadProgressChangedEventArgs e)
{
double bytesIn = double.Parse(e.BytesReceived.ToString());
double totalBytes = double.Parse(e.TotalBytesToReceive.ToString());
double percentage = bytesIn / totalBytes * 100;
progressBar1.Value = int.Parse(Math.Truncate(percentage).ToString());
}
【问题讨论】:
-
您可能对此相关问题感兴趣:Calling an asynchronous method serially
标签: c# asynchronous webclient