控制台应用程序中的可靠计时器 [英] Reliable timer in a console application

查看:116
本文介绍了控制台应用程序中的可靠计时器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am aware that in .NET there 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.

此计时器在控件中的工作方式计时器的另一个线程上,因此它总是可以在不忙的时候与父线程上开始的工作一起计时。

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.

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

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

推荐答案

您可以使用 Console.ReadLine()之类的东西来阻塞主线程,因此其他后台线程(例如计时器线程)仍然可以使用。您也可以使用 AutoResetEvent 来阻止执行,然后(在需要时)可以在该AutoResetEvent对象上调用Set()方法以释放主线程。另外,请确保对Timer对象的引用不会超出范围并不会收集垃圾。

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.

这篇关于控制台应用程序中的可靠计时器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆