计算剩余下载时间的估计

时间:2013-04-08 07:56:12

标签: c#

这是我的估计时间码。它正在运作,但当时有一个错误。

if ((DateTime.Now - _startDate).Seconds > 0)
{
    kbPerSecond = (int)((100 * 1000) / 8);
}
long sent = (TotalBytes - BytesRead);
long remainingseconds = sent / kbPerSecond;
string remainingTimeDisplay = string.Empty;
if (remainingseconds > 0)
{
    if (remainingseconds > 60)
    {
        if (remainingseconds > 3600)
        {
            remainingTimeDisplay += ((int)(remainingseconds) / 3600).ToString("n0") + " Hours, ";
            remainingseconds %= 3600;
        }
        remainingTimeDisplay += (((int)remainingseconds) / 60).ToString("n0") + " Minutes,  ";
        remainingseconds %= 60;
    }
    remainingTimeDisplay += ((int)remainingseconds).ToString("n0") + " Seconds remaining";
    lbl_estimate.Text = remainingTimeDisplay;
}

问题在于下载完成后,估计的时间将显示为“剩余1秒”而不是零。

我做错了什么?

3 个答案:

答案 0 :(得分:2)

只有在remainingseconds超过0时才能更改文字。您需要在else if if (remainingseconds > 0) { if (remainingseconds > 60) { if (remainingseconds > 3600) { remainingTimeDisplay += ((int)(remainingseconds) / 3600).ToString("n0") + " Hours, "; remainingseconds %= 3600; } remainingTimeDisplay += (((int)remainingseconds) / 60).ToString("n0") + " Minutes, "; remainingseconds %= 60; } remainingTimeDisplay += ((int)remainingseconds).ToString("n0") + " Seconds remaining"; lbl_estimate.Text = remainingTimeDisplay; } else lbl_estimate.Text = "0 seconds"; 进行更改,因此您需要以下内容:

{{1}}

答案 1 :(得分:1)

您的数据速率是常数

kbPerSecond = (int)((100 * 1000) / 8);

那不对。

答案 2 :(得分:1)

为了简化这一点,您应该提取出格式化持续时间字符串的所有逻辑。该逻辑不属于该功能的其余部分!

此外,您可以使用TimeSpan

来简化它
public static string FormatDurationSeconds(int seconds)
{
    var duration = TimeSpan.FromSeconds(seconds);
    string result = "";

    if (duration.TotalHours >= 1)
        result += (int) duration.TotalHours + " Hours, ";

    result += String.Format("{0:%m} Minutes, {0:%s} Seconds", duration);
    return result;
}

完成后,应该可以更容易地查看为什么秒数错误。