Thật khó để tìm thấy một ví dụ về mã tải xuống nhiều tệp bằng phương thức không đồng bộ của lớp webclient, nhưng mỗi lần tải xuống một tệp.Làm cách nào để tôi đồng bộ tải xuống nhiều tệp bằng cách sử dụng webclient, nhưng mỗi lần một tệp?
Tôi làm cách nào để bắt đầu tải xuống không đồng bộ, nhưng đợi cho đến khi lần đầu tiên được hoàn thành cho đến lần thứ hai, v.v ... Về cơ bản, một hàng đợi.
(lưu ý tôi không muốn sử dụng phương pháp đồng bộ, vì các chức năng tăng của phương pháp async.)
Mã dưới đây bắt đầu tất cả các tải của tôi cùng một lúc. (Thanh tiến trình là ở khắp mọi nơi)
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());
}
Bạn có thể quan tâm trong câu hỏi có liên quan này: [Kêu gọi một phương pháp không đồng bộ nối tiếp] (http://stackoverflow.com/questions/3909063/calling-an-asynchronous-method-serially) – Benjol