带进度条的异步文件下载 [英] Asynchronous File Download with Progress Bar

查看:26
本文介绍了带进度条的异步文件下载的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图在 WebClient 下载进度更改时更改进度条的进度.此代码仍会下载文件,但当我调用 startDownload() 时,窗口在下载文件时会冻结.我希望用户能够在启动画面加载时看到进度变化.有没有办法解决这个问题,以便用户可以看到 progressBar2 更改的进度?

I am attempting to have a progress bar's progress change as the WebClient download progress changes. This code still downloads the file yet when I call startDownload() the window freezes as it downloads the file. I would like for the user to be able to see the progress change as the splash screen loads. Is there any way to fix this so that the user can see the progress of progressBar2 change?

private void startDownload()
{
    WebClient client = new WebClient();
    client.DownloadProgressChanged += new DownloadProgressChangedEventHandler(client_DownloadProgressChanged);
    client.DownloadFileCompleted += new AsyncCompletedEventHandler(client_DownloadFileCompleted);
    client.DownloadFileAsync(new Uri("http://joshua-ferrara.com/luahelper/lua.syn"), @"C:LUAHelperSyntax Fileslua.syn");
}
void client_DownloadProgressChanged(object sender, DownloadProgressChangedEventArgs e)
{
    double bytesIn = double.Parse(e.BytesReceived.ToString());
    double totalBytes = double.Parse(e.TotalBytesToReceive.ToString());
    double percentage = bytesIn / totalBytes * 100;
    label2.Text = "Downloaded " + e.BytesReceived + " of " + e.TotalBytesToReceive;
    progressBar1.Value = int.Parse(Math.Truncate(percentage).ToString());
}
void client_DownloadFileCompleted(object sender, AsyncCompletedEventArgs e)
{
    label2.Text = "Completed";
}

推荐答案

您应该从 UI 线程调用 startDownload().WebClient.DownloadFileAsync() 的整个想法是它会自动为您生成一个工作线程,而不会阻塞调用线程.在 startDownload() 中,您指定了修改控件的回调,我认为这些控件是由 UI 线程创建的.因此,如果您从后台线程调用 startDownload() 它将导致问题,因为线程只能修改它创建的 UI 元素.

You should call startDownload() from the UI thread. The whole idea of WebClient.DownloadFileAsync() is that it will spawn a worker thread for you automatically without blocking the calling thread. In startDownload(), you specified callbacks that modify controls which I assume were created by the UI thread. Thus if you call startDownload() from a background thread it will cause problems, because a thread can only modify UI elements it created.

它应该工作的方式是你从 UI 线程调用 startDownload()startDownload() 按照你的定义它设置处理的事件回调通过 UI 线程.然后异步开始下载并立即返回.进度变化时会通知UI线程,负责更新进度条控件的代码会在UI线程上执行,应该不会有什么问题.

The way it is supposed to work is you call startDownload() from the UI thread, startDownload() as you defined it sets up event call backs that are handled by the UI thread. It then starts the download asynchronously and returns immediately. The UI thread will be notified when the progress changes and the code responsible for updating the progress bar control will execute on the UI thread, and there shouldn't be any problems.

这篇关于带进度条的异步文件下载的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆