
在 C# 中,定时器是一种常用的机制,可以周期性地执行某个任务或事件。常见的定时器有 System.Timers.Timer 和 System.Threading.Timer,它们在使用上有所不同,但都可以满足基本的定时功能。
然而,在某些场景下,我们需要使用定时器的高级用法,以满足更高的要求。比如,需要占用资源极少、准确度极高的定时器,以避免在高负载情况下出现性能问题,或者需要精确控制定时器的执行时间,以确保任务的准确性和稳定性。
下面介绍一些 C# 中定时器的高级用法,可以帮助我们实现占用资源极少、准确度极高的定时器。
- 使用 System.Threading.Timer 和 ManualResetEventSlim
System.Threading.Timer 是一种轻量级的定时器,可以设置回调函数和时间间隔。为了占用资源更少,可以使用 ManualResetEventSlim 对回调函数进行同步处理。
具体实现方法如下:
private static Timer _timer;
private static ManualResetEventSlim _resetEvent;
public static void StartTimer(TimeSpan interval, Action action)
{
_resetEvent = new ManualResetEventSlim(false);
_timer = new Timer(state => action(), null, TimeSpan.Zero, interval);
}
public static void StopTimer()
{
_resetEvent.
2万+



被折叠的 条评论
为什么被折叠?



