Reliable timer in a console application

我知道在 .NET中有三种定时器类型(参见 比较.NET Framework 类库中的 Timer 类)。我已经选择了一个线程计时器,因为其他类型可以漂移,如果主线程繁忙,我需要这是可靠的。

The way this timer works in the control of the timer is put on another thread so it can always tick along with the work begin completed on the parent thread when it is not busy.

这个定时控制台应用的问题在于,当定时器在另一个线程上运行时,主线程不会对应用程序做任何事情。

I tried adding a while true loop, but then the main thread is too busy when the timer does go off.

7931 次浏览

考虑使用 手动重置事件在主线程的处理结束时阻塞它,并在计时器的处理结束后调用它的 Reset()。如果这是需要连续运行的东西,考虑将其移动到服务进程而不是控制台应用程序中。

You can use something like Console.ReadLine() to block the main thread, so other background threads (like timer threads) will still work. You may also use an AutoResetEvent to block the execution, then (when you need to) you can call Set() method on that AutoResetEvent object to release the main thread. Also ensure that your reference to Timer object doesn't go out of scope and garbage collected.

根据 MSDN和其他答案,一个使用系统的控制台应用的最小工作示例。穿线。不立即退出的计时器:

private static void Main()
{
using AutoResetEvent autoResetEvent = new AutoResetEvent(false);
using Timer timer = new Timer(state => Console.WriteLine("One second has passed"), autoResetEvent, TimeSpan.Zero, new TimeSpan(0, 0, 1));
autoResetEvent.WaitOne();
}