【问题标题】:C# WebClient Download Time LeftC# WebClient 下载剩余时间
【发布时间】:2015-08-08 05:44:40
【问题描述】:

我试图在我的 C# 下载表单中显示一个剩余时间标签,它类似于 chrome 等浏览器。我已经尝试了以下基于 java 对堆栈溢出问题的相同问题的回答,但它真的很不稳定:Goes to negatives, hours go up and down fast as the minutes etc.

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 下载剩余时间的最佳方法?

【问题讨论】:

标签: c# .net webclient


【解决方案1】:
var elapsedTime = DateTime.Now.Second - _startTime.Second;

DateTime.Second 仅返回秒组件,表示为 0 到 59 之间的值。这可能导致非常意外的行为,因为 63 秒延迟将被视为仅持续 3 秒(模 60)。

您需要小心使用全职组件。例如,您可以使用TimeSpan.TotalSeconds

var elapsedTime = (DateTime.Now - _startTime).TotalSeconds;

【讨论】:

  • @AmitKumarGhosh:不。TotalMilliseconds 会起作用,但实际上并没有什么不同,因为 TotalSecondsdouble 并提供相同的精度。
猜你喜欢
  • 1970-01-01
  • 2011-03-27
  • 1970-01-01
  • 2011-02-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多