Skip to main content
 首页 » 编程设计

c#之帮助下载进度条

2024年02月23日19Free-Thinker

我试图制作一个简单的下载器,但我无法更新我的表单 (Form1) 中的 GUI 元素。

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

        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"; 
} 

请您参考如下方法:

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

此外,这就是为什么 DownloadProgressChanged 事件没有触发的原因:

它只适用于异步调用 (link) .