进度条无法正常工作

时间:2012-07-27 15:29:38

标签: 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");
    }

但事件并不是为什么? 这是因为后台工作者还是其他任何问题?

请帮帮我。

致以最诚挚的问候,

2 个答案:

答案 0 :(得分:1)

我认为这是因为更新的进度是在后台线程而不是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");   

}   

答案 1 :(得分:0)

您的进度条必须符合以下条件:

-Accurate - 反应顺畅 -精确 - 适当