所以我使用webClient.DownloadFileAsync(url, sFilePathToWriteFileTo);
下载文件
网址为string url = "http://localhost/1.zip";
sFilePathToWriteFileTo是根目录
每当我下载500mb zip存档时,我的label1变为狂暴并说“使用INF kb / s下载”,这就是它何时开始没有响应并崩溃
label1为label1.Text = string.Format("Downloading with {0} kb/s", (e.BytesReceived / 1024d / sw.Elapsed.TotalSeconds).ToString("0.00"));
当我下载低尺寸文件,20mb-50mb
时,它完全正常哦顺便说一句,(我只是重新阅读了我的帖子),sw是StopWatch,你想知道
这里有什么问题,我该如何解决?
- 编辑,添加了webClient:
using (webClient = new WebClient())
{
webClient.DownloadFileCompleted += new AsyncCompletedEventHandler(wzCompleted);
webClient.DownloadProgressChanged += new DownloadProgressChangedEventHandler(wzProgressChanged);
Uri url = new Uri(sUrlToReadFileFrom);
sw.Start();
try
{
webClient.DownloadFileAsync(url, sFilePathToWriteFileTo);
}
catch (Exception ex)
{
downloadInfo.Text = ex.Message;
}
}
wzProgressChanged:
private void wzProgressChanged(object sender, DownloadProgressChangedEventArgs e)
{
statusContent.Text = "Downloading new game files";
downloadInfo.Text = "Downloading: " + string.Format("{0} MB / {1} MB", (e.BytesReceived / 1024d / 1024d).ToString("0.00"), (e.TotalBytesToReceive / 1024d / 1024d).ToString("0.00")) + " with " + string.Format("{0} kb/s", (e.BytesReceived / 1024d / sw.Elapsed.TotalSeconds).ToString("0.00")) + " (" + e.ProgressPercentage.ToString() + "%" + ")";
progressBar1.Value = e.ProgressPercentage;
}
wzCompleted: 它只是启用2个按钮并禁用其他2个按钮,不需要这个吗?
答案 0 :(得分:0)
在wzProgressChanged
处理程序中做3件事:
sw.Elapsed.TotalSeconds
不为零以避免除以零阅读有关InvokeRequired的文档。它将告诉您有关UI线程以及如何确保正确更新UI的所有信息。我会让代码看起来像这样(没有经过测试甚至编译但非常接近)
private void wzProgressChanged(object sender, DownloadProgressChangedEventArgs e)
{
if (this.InvokeRequired)
{
this.Invoke(() => wzProgressChanged(sender, e));
}
else if (sw.Elapsed.TotalSeconds > 0)
{
try
{
statusContent.Text = "Downloading new game files";
downloadInfo.Text = "Downloading: " + string.Format("{0} MB / {1} MB", (e.BytesReceived / 1024d / 1024d).ToString("0.00"), (e.TotalBytesToReceive / 1024d / 1024d).ToString("0.00")) + " with " + string.Format("{0} kb/s", (e.BytesReceived / 1024d / sw.Elapsed.TotalSeconds).ToString("0.00")) + " (" + e.ProgressPercentage.ToString() + "%" + ")";
progressBar1.Value = e.ProgressPercentage;
}
catch(Exception e)
{
System.Diagnostics.Debug.WriteLine(e.Message);
}
}
}
答案 1 :(得分:0)
除了dkackman建议的内容之外,我还建议您更新一下您更新标签的频率,并可能对您的值进行额外检查,以确保您没有获得值NaN / INF值。请参阅other posts此处了解其确切含义。查看Double.IsInfinity等方法,以帮助您确定您的计算结果是否产生了可以显示的数字。
此外,在字符串格式声明之外进行一些计算,并根据您的发现,您可以决定向用户提供哪些信息。