C# 控制台应用程序中的可靠计时器

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/39/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-07-31 09:43:21  来源:igfitidea点击:

Reliable timer in a console application

提问by John

I am aware that in .NETthere are three timer types (see Comparing the Timer Classes in the .NET Framework Class Library). I have chosen a threaded timer as the other types can drift if the main thread is busy, and I need this to be reliable.

我知道在.NET 中有三种计时器类型(请参阅比较 .NET Framework 类库中的计时器类)。我选择了一个线程计时器,因为如果主线程很忙,其他类型的计时器可能会漂移,我需要它是可靠的。

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.

这个计时器在计时器控制中的工作方式被放在另一个线程上,因此它可以在父线程不忙时随着工作开始在父线程上完成打勾。

The issue with this timer in a console application is that while the timer is ticking along on another thread the main thread is not doing anything to the application closes.

这个计时器在控制台应用程序中的问题是,当计时器在另一个线程上滴答作响时,主线程没有对应用程序关闭做任何事情。

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

我尝试添加一个while true循环,但是当计时器关闭时主线程太忙了。

采纳答案by huseyint

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 AutoResetEventto 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.

您可以使用类似的方法Console.ReadLine()来阻塞主线程,以便其他后台线程(如计时器线程)仍然可以工作。您也可以使用AutoResetEvent来阻止执行,然后(当您需要时)您可以在该 AutoResetEvent 对象上调用 Set() 方法以释放主线程。还要确保您对 Timer 对象的引用不会超出范围和垃圾收集。

回答by Greg Hurlman

Consider using a ManualResetEventto block the main thread at the end of its processing, and call Reset()on it once the timer's processing has finished. If this is something that needs to run continuously, consider moving this into a service process instead of a console app.

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