简体   繁体   English

进度栏无法正常工作

[英]Progress bar is not working correctly

I just tried to write code for a progress bar with webclient Please see my code. 我刚刚尝试使用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");
    }

But the event is not calling why? 但是事件没有调用为什么? is this because of the background worker or any other issues? 是因为后台工作人员还是其他问题?

Please help me. 请帮我。

Best regards, 最好的祝福,

I think it is because the progress updated is called on a background thread and not the UI thread. 我认为这是因为更新的进度是在后台线程而不是UI线程上调用的。 Try passing in the webclient to the DoWork thread: 尝试将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");   

}   

Your Progress Bar must be of the following conditions : 您的进度栏必须满足以下条件:

-Accurate -Responsive and smooth -Precise -Appropriate -准确-反应灵敏且平稳-精确-适当

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM