c# - 如何在控制台中显示运行时间?

标签 c# console-application timespan

C# 我需要在进程运行时显示运行时间,显示秒数增加,通常为:00:00:01、00:00:02、00:00:03 ......等等。

我正在使用这段代码:

var stopwatch = new System.Diagnostics.Stopwatch();
stopwatch.Start();

//here is doing my process
stopwatch.Stop();

当进程停止时,我会显示 ELAPSED 时间:

TimeSpan ts = stopwatch.Elapsed;

...还有这个:

{0} minute(s)"+ " {1} second(s)", ts.Minutes, ts.Seconds, ts.Milliseconds/10.

这显示了总耗时,但我需要在控制台中显示运行时间。

我该怎么做?

最佳答案

尝试

Stopwatch stopwatch = new Stopwatch();
stopwatch.Start();
while (true)
{
    Console.Write(stopwatch.Elapsed.ToString());
    Console.Write('\r');
}

更新

要防止显示毫秒:

        Stopwatch stopwatch = new Stopwatch();
        stopwatch.Start();
        while (true)
        {
            TimeSpan timeSpan = TimeSpan.FromSeconds(Convert.ToInt32(stopwatch.Elapsed.TotalSeconds));
            Console.Write(timeSpan.ToString("c"));
            Console.Write('\r');
        }

关于c# - 如何在控制台中显示运行时间?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5717527/

相关文章:

c# - 使用 Mvvm Helpers 进行数据绑定(bind)

c# - WebAPI 2 中的 DefaultInlineConstraintResolver 错误

c# - Linq to SQL 立即执行查询

c# - 32 位和 64 位 Windows 之间的日期时间粒度

c# - 为什么 TimeSpan 没有 Years 属性?

c# - 我得到 String was not recognized as a valid DateTime error on some strings that worked for previous rows

c# - OWIN 无法以 "The network location cannot be reached"开头

c++ - 在神秘的情况下,QCoreApplication 的用户参数为空

c# - 需要帮助使用循环使 Console.Writeline block 更高效

c# - String.Format 和 TimeSpan 问题