【发布时间】:2021-11-30 11:58:02
【问题描述】:
我制作了一个计时器,可以每秒刷新 Console.Title 上的时间,但它不起作用,它永远不会刷新。它总是在 00:00:00。 每秒刷新一次怎么办?谢谢!
public static int current_hour = 0;
public static int current_minute = 0;
public static int current_seconds = 0;
Console.Title = $"Elapsed time: {current_hour.ToString().PadLeft(2, '0')}:{current_minute.ToString().PadLeft(2, '0')}:{current_seconds.ToString().PadLeft(2, '0')}";
这里是函数。
public static void Timer_Elapsed(object sender, ElapsedEventArgs e)
{
Constants.current_seconds++;
if (Constants.current_seconds.Equals(60))
{
current_seconds = 0;
current_minute++;
if (Constants.current_minute.Equals(60))
{
current_minute = 0;
current_hour++;
}
}
GC.Collect();
}
这是用户在控制台上按下 Start 时运行经过时间的代码
System.Timers.Timer clockcount = new System.Timers.Timer();
clockcount.AutoReset = true;
clockcount.Interval = 1000;
clockcount.Elapsed += Timer_Elapsed;
lockcount.Enabled = true;
clockcount.Start();
【问题讨论】:
-
计时器没有那么精确。不要增加变量,而是使用
DateTime.Now或Stopwatch以获得更好的时机。 -
你在哪里更新
Console.Title?我只能在您的代码中看到它被初始化一次。如果您希望它在计时器触发时更新,您需要从Timer_Elapsed()内部直接(或间接)更新它。
标签: c# chronometer system.timers.timer