前言

上文给大家介绍了 TimerQueue 的任务调度算法。
https://www.cnblogs.com/eventhorizon/p/17557821.html

这边做一个简单的复习。

TimerQueue 中的基本任务单元是 TimerQueueTimer,封装待执行的定时任务。

TimeQueue 按照任务到期时间分为 shortTimer 和 longTimer 两个队列,分别存储在 TimerQueue 的 shortTimers 和 longTimers
这两个双向链表中。

Runtime 按照 CPU 核心数创建相同数量的 TimerQueue,每个 TimerQueueTimer 会根据其创建时所在的 CPU 核心,被分配到对应的
TimerQueue 中,并按照任务到期时间,插入到对应的 shortTimer 或 longTimer 队列中。

每个 TimerQueue 会根据它所管理的 TimerQueueTimer 的到期时间,维护一个最小到期时间,这个最小到期时间就是 TimerQueue 自己的到期时间,
TimerQueue 会将自己的到期时间注册到 操作系统(后面简称 OS)的定时器中。

当 OS 的定时器到期时,会通知 TimerQueue,TimerQueue 会将到期的 TimerQueueTimer 从 shortTimer 或 longTimer
队列中移除并将定时任务放入到线程池中执行。

上文给大家主要介绍了 TimerQueue 对于 TimerQueueTimer 的管理,而本文将基于. NET 7 版本的代码介绍 TimerQueue 是如何与 OS
的定时器进行交互的。

TimerQueue 与 OS 定时器的交互

按需注册定时器

TimerQueue 向 OS 注册定时器的过程被封装在 TimerQueueTimer 的 EnsureTimerFiresBy 方法中。
有两处地方会调用 EnsureTimerFiresBy 方法

  1. UpdateTimer 方法,此方法用于注册或更新 TimerQueueTimer。

  2. FireNextTimers 方法中,此方法用于遍历和执行 TimerQueue 中的 TimerQueueTimer。如果遍历完所有到期的 TimerQueueTimer 后,发现
    TimerQueue 中还有未到期的
    TimerQueueTimer,那么会调用 EnsureTimerFiresBy 方法,保证后面到期的 TimerQueueTimer 能够被及时执行。

internal class TimerQueue : IThreadPoolWorkItem
{
    private bool _isTimerScheduled;
    private long _currentTimerStartTicks;
    private uint _currentTimerDuration;
    
    private bool EnsureTimerFiresBy(uint requestedDuration)
    {
        // TimerQueue 会将 requestedDuration 限制在 0x0fffffff 以内
        // 0x0fffffff = 268435455 = 0x0fffffff / 1000 / 60 / 60 / 24 = 3.11 天
        // 也就是说,runtime 会将 requestedDuration 限制在 3.11 天以内
        // 因为 runtime 的定时器实现对于很长时间的定时器不太好用
        // OS 的定时器可能会提前触发,但是这没关系,TimerQueue 会检查定时器是否到期,如果没有到期,TimerQueue 会重新注册定时器
        const uint maxPossibleDuration = 0x0fffffff;
        uint actualDuration = Math.Min(requestedDuration, maxPossibleDuration);

        if (_isTimerScheduled)
        {
            long elapsed = TickCount64 - _currentTimerStartTicks;
            if (elapsed >= _currentTimerDuration)
                return true; // 当前定时器已经到期,不需要重新注册定时器

            uint remainingDuration = _currentTimerDuration - (uint)elapsed;
            if (actualDuration >= remainingDuration)
                return true; // 当前定时器的到期时间早于 requestedDuration,不需要重新注册定时器
        }

        // 注册定时器
        if (SetTimer(actualDuration))
        {
            _isTimerScheduled = true;
            _currentTimerStartTicks = TickCount64;
            _currentTimerDuration = actualDuration;
            return true;
        }

        return false;
    }
}

在 EnsureTimerFiresBy 方法中,会记录当前 TimerQueue 的到期时间和状态,按需判断是否需要重新注册定时器。

AutoResetEvent 封装 OS 定时器

在进一步介绍 TimerQueue 是如何与 OS 的定时器进行交互之前,我们先来看一下 AutoResetEvent。

TimerQueue 使用了一个 AutoResetEvent 来等待定时器到期,封装了和 OS 定时器的交互。

AutoResetEvent 是一个线程同步的基元,它封装了一个内核对象,这个内核对象的状态有两种:终止状态和非终止状态,通过构造函数的
initialState 参数指定。

当调用 AutoResetEvent.WaitOne() 时,如果 AutoResetEvent 的状态为非终止状态,那么当前线程会被阻塞,直到 AutoResetEvent
的状态变为终止状态。

当调用 AutoResetEvent.Set() 时,如果 AutoResetEvent 的状态为非终止状态,那么 AutoResetEvent 的状态会变为终止状态,并且会唤醒一个等待的线程。

当调用 AutoResetEvent.Set() 时,如果 AutoResetEvent 的状态为终止状态,那么 AutoResetEvent 的状态不会发生变化,也不会唤醒等待的线程。

// 初始化为非终止状态,调用 WaitOne 会被阻塞
var autoResetEvent = new AutoResetEvent(initialState: false);
Task.Run(() =>
{
    Console.WriteLine($"Task start {DateTime.Now:HH:mm:ss.fff}");
    // 等待 Set 方法的调用,将 AutoResetEvent 的状态变为终止状态
    autoResetEvent.WaitOne();
    Console.WriteLine($"WaitOne1 end {DateTime.Now:HH:mm:ss.fff}");
    // 每次被唤醒后,都会重新进入阻塞状态,等待下一次的唤醒
    autoResetEvent.WaitOne();
    Console.WriteLine($"WaitOne2 end {DateTime.Now:HH:mm:ss.fff}");
});

Thread.Sleep(1000);
autoResetEvent.Set();
Thread.Sleep(2000);
autoResetEvent.Set();

Console.ReadLine();

输出结果如下

Task start 10:42:39.914
WaitOne1 end 10:42:40.916
WaitOne2 end 10:42:42.918

同时,AutoResetEvent 还提供了 WaitOne 方法的重载,可以指定等待的时间。如果在指定的时间内,AutoResetEvent 的状态没有变为终止状态,那么 WaitOne 停止等待,唤醒线程。

public virtual bool WaitOne(TimeSpan timeout)
public virtual bool WaitOne(int millisecondsTimeout)
var autoResetEvent = new AutoResetEvent(false);
Task.Run(() =>
{
    Console.WriteLine($"Task start {DateTime.Now:HH:mm:ss.fff}");
    // 虽然 Set 方法在 2 秒后执行,但因为 WaitOne 方法的超时时间为 1 秒,所以 1 秒后就会执行下面的代码
    autoResetEvent.WaitOne(TimeSpan.FromSeconds(1));
    Console.WriteLine($"Task end {DateTime.Now:HH:mm:ss.fff}");
});

Thread.Sleep(2000);
autoResetEvent.Set();

Console.ReadLine();

输出结果如下

Task start 10:51:36.412
Task end 10:51:37.600

定时任务的管理

接下来我们看一下 SetTimer 方法的实现。

我们一共需要关注下面三个方法

  1. SetTimer:用于注册定时器
  2. InitializeScheduledTimerManager_Locked:只会被调用一次,用于初始化 TimerQueue 的定时器管理器,主要是初始化 TimerThread。
  3. TimerThread:用于处理 OS 定时器到期的线程,所有的 TimerQueue 共用一个 TimerThread。TimerThread 会在 OS 定时器到期时被唤醒,然后会遍历所有的 TimerQueue,找到到期的
    TimerQueue,然后将到期的 TimerQueue 放入到线程池中执行。
// TimerQueue 实现了 IThreadPoolWorkItem 接口,这意味着 TimerQueue 可以被放入到线程池中执行
internal class TimerQueue : IThreadPoolWorkItem
{
    private static List<TimerQueue>? s_scheduledTimers;
    private static List<TimerQueue>? s_scheduledTimersToFire;

    // TimerQueue 使用了一个 AutoResetEvent 来等待定时器到期,封装了和 OS 定时器的交互
    // intialState = false,表示 AutoResetEvent 的初始状态为非终止状态
    // 这样,当调用 AutoResetEvent.WaitOne() 时,因为 AutoResetEvent 的状态为非终止状态,那么调用线程会被阻塞
    // 被阻塞的线程会在 AutoResetEvent.Set() 被调用时被唤醒
    // AutoResetEvent 在被唤醒后,会将自己的状态设置为非终止状态,这样,下一次调用 AutoResetEvent.WaitOne() 时,调用线程会被阻塞
    private static readonly AutoResetEvent s_timerEvent = new AutoResetEvent(false);

    private bool _isScheduled;
    private long _scheduledDueTimeMs;

    private bool SetTimer(uint actualDuration)
    {
        long dueTimeMs = TickCount64 + (int)actualDuration;
        AutoResetEvent timerEvent = s_timerEvent;
        lock (timerEvent)
        {
            if (!_isScheduled)
            {
                List<TimerQueue> timers = s_scheduledTimers ?? InitializeScheduledTimerManager_Locked();

                timers.Add(this);
                _isScheduled = true;
            }

            _scheduledDueTimeMs = dueTimeMs;
        }

        // 调用 AutoResetEvent.Set(),唤醒 TimerThread
        timerEvent.Set();
        return true;
    }

    private static List<TimerQueue> InitializeScheduledTimerManager_Locked()
    {
        var timers = new List<TimerQueue>(Instances.Length);
        s_scheduledTimersToFire ??= new List<TimerQueue>(Instances.Length);

        Thread timerThread = new Thread(TimerThread)
        {
            Name = ".NET Timer",
            IsBackground = true // 后台线程,当所有前台线程都结束时,后台线程会自动结束
        };
        // 使用 UnsafeStart 方法启动线程,是为了避免 ExecutionContext 的传播
        timerThread.UnsafeStart();

        // 这边是个设计上的细节,如果创建线程失败,那么会在下次创建线程时再次尝试
        s_scheduledTimers = timers;
        return timers;
    }

    // 这个方法会在一个专用的线程上执行,它的作用是处理定时器请求,并在定时器到期时通知 TimerQueue
    private static void TimerThread()
    {
        AutoResetEvent timerEvent = s_timerEvent;
        List<TimerQueue> timersToFire = s_scheduledTimersToFire!;
        List<TimerQueue> timers;
        lock (timerEvent)
        {
            timers = s_scheduledTimers!;
        }

        // 初始的Timeout.Infinite表示永不超时,也就是说,一开始只有等到 AutoResetEvent.Set() 被调用时,线程才会被唤醒
        int shortestWaitDurationMs = Timeout.Infinite;
        while (true)
        {
            // 等待定时器到期或者被唤醒
            timerEvent.WaitOne(shortestWaitDurationMs);

            long currentTimeMs = TickCount64;
            shortestWaitDurationMs = int.MaxValue;
            lock (timerEvent)
            {
                // 遍历所有的 TimerQueue,找到到期的 TimerQueue
                for (int i = timers.Count - 1; i >= 0; --i)
                {
                    TimerQueue timer = timers[i];
                    long waitDurationMs = timer._scheduledDueTimeMs - currentTimeMs;
                    if (waitDurationMs <= 0)
                    {
                        timer._isScheduled = false;
                        timersToFire.Add(timer);

                        int lastIndex = timers.Count - 1;
                        if (i != lastIndex)
                        {
                            timers[i] = timers[lastIndex];
                        }

                        timers.RemoveAt(lastIndex);
                        continue;
                    }
                    
                    // 找到最短的等待时间
                    if (waitDurationMs < shortestWaitDurationMs)
                    {
                        shortestWaitDurationMs = (int)waitDurationMs;
                    }
                }
            }

            if (timersToFire.Count > 0)
            {
                foreach (TimerQueue timerToFire in timersToFire)
                {
                    // 将到期的 TimerQueue 放入到线程池中执行
                    // UnsafeQueueHighPriorityWorkItemInternal 方法会将 timerToFire 放入到线程池的高优先级队列中,这个是 .NET 7 中新增的功能
                    ThreadPool.UnsafeQueueHighPriorityWorkItemInternal(timerToFire);
                }

                timersToFire.Clear();
            }

            if (shortestWaitDurationMs == int.MaxValue)
            {
                shortestWaitDurationMs = Timeout.Infinite;
            }
        }
    }

    void IThreadPoolWorkItem.Execute() => FireNextTimers();
}

所有的 TimerQueue 共享一个 AutoResetEvent 和一个 TimerThread,当 AutoResetEvent.Set() 被调用或者OS定时器到期时,TimerThread 会被唤醒,然后 TimerThread
会遍历所有的 TimerQueue,找到到期的 TimerQueue,然后将到期的 TimerQueue 放入到线程池中执行。

这样,就实现了 TimerQueue 的定时器管理器。

总结

TimerQueue 的实现是一个套娃的过程。

TimerQueue 使用了一个 AutoResetEvent 来等待定时器到期,封装了和 OS 定时器的交互,然后 TimerQueue 实现了 IThreadPoolWorkItem 接口,这意味着 TimerQueue 可以被放入到线程池中执行。

TimerQueue 的定时器管理器是一个专用的线程,它会等待 AutoResetEvent.Set() 被调用或者OS定时器到期时被唤醒,然后遍历所有的 TimerQueue,找到到期的 TimerQueue,然后将到期的 TimerQueue 放入到线程池中执行。

TimerQueue 在被放入到线程池中执行时,会调用 FireNextTimers 方法,这个方法会遍历 TimerQueue 保存的 TimerQueueTimer,找到到期的 TimerQueueTimer,然后将到期的
TimerQueueTimer 放入到线程池中执行。

欢迎关注个人技术公众号
揭秘 .NET 中的 TimerQueue(下)-LMLPHP

08-07 08:32