[英]DownloadFileAsync application not responding if file is over 500mb?
所以我正在使用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個其他按鈕,不需要嗎?
在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);
}
}
}
除了dkackman提出的建議之外,我還建議您對標簽的更新頻率有更多的選擇,並可能對值進行一些額外的檢查,以確保您不會在NaN / INF中得到值。 請參閱此處的其他帖子 ,了解它們的確切含義。 查看類似Double.IsInfinity的方法,以幫助您確定您的計算是否導致可以顯示的數字。
另外,在字符串格式語句之外進行一些計算,並根據發現,可以確定要提供給用戶的信息。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.