[英]C# WebClient Download Time Left
我試圖在我的 C# 下載表單中顯示一個 Time Left 標簽,它類似於 chrome 等瀏覽器的標簽。 我已經嘗試了以下基於 Java 對堆棧溢出相同問題的回答,但它確實不穩定:轉到負數,小時數快速上升和下降數分鍾等。
var elapsedTime = DateTime.Now.Second - _startTime.Second;
var allTimeFordownloading = (elapsedTime * e.TotalBytesToReceive / e.BytesReceived);
var remainingTime = allTimeFordownloading - elapsedTime;
TimeSpan time = TimeSpan.FromSeconds(remainingTime);
TimeRemaining.Text = string.Format("Time Remaining: {0} Minutes, {1} Seconds", time.Minutes, time.Seconds);
Progress.Value = e.ProgressPercentage;
DownloadPercentage.Text = string.Format("{0}/100%", e.ProgressPercentage);
if (e.BytesReceived < 1024)
BytesLeft.Text = string.Format("{0}/{1} KBs", Math.Round(e.BytesReceived / 1024f), Math.Round(e.TotalBytesToReceive / 1024f));
else
BytesLeft.Text = string.Format("{0}/{1} MBs", (Math.Round((e.BytesReceived / 1024f) / 1024f)), Math.Round((e.TotalBytesToReceive / 1024f) / 1024f));
_startTime 是在調用 DownloadFileAsync 方法之前開始的 DateTime。 Progress 是表單上 ProgressBar 的名稱,e 是傳遞給事件處理程序的 DownloadProgressChangedEventArgs 對象。
編輯:我的問題是計算 C# WebClient 下載剩余時間的最佳方法?
var elapsedTime = DateTime.Now.Second - _startTime.Second;
DateTime.Second
只返回秒部分,表示為 0 到 59 之間的值。這可能會導致非常意外的行為,因為 63 秒的延遲將被視為僅持續 3 秒(模 60)。
您需要小心處理全職組件。 例如,您可以使用TimeSpan.TotalSeconds
:
var elapsedTime = (DateTime.Now - _startTime).TotalSeconds;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.