【发布时间】:2025-12-08 23:30:01
【问题描述】:
我正在尝试创建一个简单的程序来下载几个文件。我尝试了一些在网上找到的现成解决方案,但我无法让它按照我想要的方式工作。我正在使用这个:
private void startDownload(string toDownload, string saveLocation)
{
Thread thread = new Thread(() =>
{
WebClient client = new WebClient();
client.DownloadProgressChanged += new DownloadProgressChangedEventHandler(client_DownloadProgressChanged);
client.DownloadFileCompleted += new AsyncCompletedEventHandler(client_DownloadFileCompleted);
client.DownloadFileAsync(new Uri(toDownload), saveLocation);
});
thread.Start();
}
void client_DownloadProgressChanged(object sender, DownloadProgressChangedEventArgs e)
{
this.BeginInvoke((MethodInvoker)delegate
{
double bytesIn = double.Parse(e.BytesReceived.ToString());
double totalBytes = double.Parse(e.TotalBytesToReceive.ToString());
double percentage = bytesIn / totalBytes * 100;
labelPercentage.Text = "Downloading " + Convert.ToInt32(percentage) + "% - " + Convert.ToInt32(bytesIn / 1024) + " / " + Convert.ToInt32(totalBytes / 1024) + " kB";
progressBar1.Value = int.Parse(Math.Truncate(percentage).ToString());
});
}
void client_DownloadFileCompleted(object sender, AsyncCompletedEventArgs e)
{
this.BeginInvoke((MethodInvoker)delegate
{
textBoxLog.AppendText("OK");
});
}
我想让程序在下载完成后继续运行(下载下一个文件/显示“OK”消息/执行下一行代码中的任何内容)。 在当前的形式中,如果我输入例如。
private void button1_Click(object sender, EventArgs e)
{
startDownload(url, localpath + @"\file.zip");
textBoxLog.AppendText("the cake is a lie");
}
它首先向我显示此文本,然后显示“OK”。
我是从 c#/.net 开始的,而且我以前从未学习过面向对象的编程,所以这对我来说是一种双重挑战,我自己也搞不清楚。如果能提供相对简单的解释,我将不胜感激。
【问题讨论】:
-
我不明白这个问题。下载完成后你已经做了。你究竟不能做什么?你尝试了什么?你被困在哪里了?
-
我将下载大约 50 个文件,这些文件将循环完成。 foreach(文件中的字符串文件) startDownload(...) 将同时下载 50 个文件,进度条将得到帕金森病,并且程序将继续执行在所有文件下载之前不应执行的操作。
-
使用 thread.Join // 等到线程完成)大线程:*.com/questions/1584062/…