gpt4 book ai didi

c# - 带进度条的异步文件下载

转载 作者:IT王子 更新时间:2023-10-29 04:29:49 25 4
gpt4 key购买 nike

我正在尝试让进度条的进度随着 WebClient 下载进度的变化而变化。此代码仍在下载文件,但当我调用 startDownload() 时,窗口在下载文件时卡住。我希望用户能够在启动画面加载时看到进度变化。有什么方法可以解决此问题,以便用户可以看到 progressBar2 更改的进度吗?

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:\LUAHelper\Syntax Files\lua.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";
}

最佳答案

当您单击startDownload() 时,UI 线程将被卡住。如果您不想卡住表单,可以在另一个线程中使用 startDownload() 并在跨线程中进行进度更新。一种方式,

private void startDownload()
{
Thread thread = new Thread(() => {
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:\LUAHelper\Syntax Files\lua.syn");
});
thread.Start();
}
void client_DownloadProgressChanged(object sender, DownloadProgressChangedEventArgs e)
{
this.BeginInvoke((MethodInvoker) delegate {
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)
{
this.BeginInvoke((MethodInvoker) delegate {
label2.Text = "Completed";
});
}

像这样在谷歌阅读更多多线程 http://msdn.microsoft.com/en-us/library/ms951089.aspx

-修复了丢失的 close );到 bgThread 声明

关于c# - 带进度条的异步文件下载,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9459225/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com