c# - 进度条无法正常工作

标签 c#

我刚刚尝试用 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/

相关文章:

c# - Hierarchyid 数据类型和 Code First

c# - 发生 "Ensure Event Failed"错误

c# - 如何仅 Ping IPv4?

c# - 返回相对图像路径的 html 帮助程序未显示图像,但在 View 中硬编码相同路径时显示

c# - Linq 到实体 (EF) : How to get the value of a FK without doing the join

c# - 如何告诉 Linq to Entities 使用 'Like' 来实现字符串相等?

c# - 在 C# 中命名变量的正确礼节是什么?

c# - 通过 Azure 信息保护统一标签客户端读取 Outlook 电子邮件中设置的 Internet header

c# - DataContract 中字典的自定义序列化

c# - MVC 编辑存储在隐藏字段中的复杂对象