我刚刚尝试用 webclient 为进度条编写代码 请查看我的代码。
private void button2_Click(object sender, EventArgs e)
{
if (textBox1.Text == "")
{
MessageBox.Show("Invalid Php Url");
}
else if (Uri.IsWellFormedUriString(textBox1.Text, UriKind.Absolute) == false)
{
MessageBox.Show("Invalid Php Url");
}
else
{
backgroundWorker1.RunWorkerAsync();
}
}
private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
WebClient client = new WebClient();
client.DownloadProgressChanged += new DownloadProgressChangedEventHandler(DownloadProgressCallback);
client.DownloadFileCompleted += new AsyncCompletedEventHandler(DownloadFileCallBack2);
client.DownloadFile(textBox1.Text, @"D:\test\test.zip");
}
void DownloadProgressCallback(object sender, DownloadProgressChangedEventArgs e)
{
this.progressBar1.Value = e.ProgressPercentage;
this.label6.Text = e.ProgressPercentage.ToString();
}
void DownloadFileCallBack2(object sender, AsyncCompletedEventArgs c)
{
MessageBox.Show("Download Completed");
}
但是事件没有调用,为什么? 是后台工作人员的问题还是其他问题?
请帮帮我。
最好的问候,
最佳答案
我认为这是因为进度更新是在后台线程而不是 UI 线程上调用的。尝试将 webclient 传递给 DoWork 线程:
WebClient client = new WebClient();
client.DownloadProgressChanged += new DownloadProgressChangedEventHandler(DownloadProgressCallback);
client.DownloadFileCompleted += new AsyncCompletedEventHandler(DownloadFileCallBack2);
backgroundWorker1.RunWorkerAsync(client);
private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
WebClient client = (WebClient)e.Argument;
client.DownloadFile(textBox1.Text, @"D:\test\test.zip");
}
关于c# - 进度条无法正常工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11690983/