帮助下载进度条

时间:2011-02-17 13:23:54

标签: c#

我试图制作一个简单的下载程序,但我不能让它更新我的表单中的GUI元素(Form1)。

在Form1的构造函数中,我调用thread:

        Thread t = new Thread(new ThreadStart(fetch));
        t.Start();

fetch看起来像这样:

private void fetch()
{
        try
        {
            WebClient webClient = new WebClient();
            webClient.DownloadProgressChanged += new DownloadProgressChangedEventHandler(webClient_DownloadProgressChanged);
            webClient.DownloadFileCompleted += new AsyncCompletedEventHandler(webClient_DownloadFileCompleted);
            webClient.DownloadFile(updateurl, @"foo.iso");
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.Message + "\n\n" + ex.InnerException.ToString());
        }
}

没有触发任何事件......但是,通过查看文件夹中的foo.iso,我看到文件大小增加。

其中一个事件如下:

void webClient_DownloadProgressChanged(object sender, DownloadProgressChangedEventArgs e)
{   
    progressBar.Value = (int)(e.BytesReceived * 100 / e.TotalBytesToReceive);

    statusLabel.Text = "Downloading";
    descLabel.Text = progressBar.Value + " % complete";
}

2 个答案:

答案 0 :(得分:2)

我不知道,为什么他们不会被提出,但问题是,您正在尝试从非UI线程更新UI。
怎么做,可以在这里看到:How to update the GUI from another thread in C#?

答案 1 :(得分:2)

您不需要在另一个线程中执行fetch方法,只需使用DownloadFileAsync而不是DownloadFile,它应该异步工作。

此外,这就是DownloadProgressChanged事件未触发的原因:

它仅适用于异步调用(link)

相关问题