首页 > 其他分享 >揭秘 .NET 中的 TimerQueue(下)

揭秘 .NET 中的 TimerQueue(下)

时间:2023-08-06 11:47:07浏览次数:42  
标签:定时器 AutoResetEvent 到期 TimerQueue 线程 NET OS 揭秘

前言

上文给大家介绍了 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 放入到线程池中执行。

欢迎关注个人技术公众号

标签:定时器,AutoResetEvent,到期,TimerQueue,线程,NET,OS,揭秘
From: https://www.cnblogs.com/eventhorizon/p/17609210.html

相关文章

  • asp.net core 源代码阅读
    阅读BCL(BaseClassLibrary)和ASP.NETCore的源代码是一项挑战性的任务,但也是提升您对这些技术理解的有效方式。以下是一些步骤和建议,可以帮助您更好地阅读和理解源代码:1.设置开发环境:确保您的开发环境已经准备就绪,包括安装了适当版本的.NETCoreSDK、VisualStudio或其他适用的I......
  • Cilium系列-14-Cilium NetworkPolicy 简介
    系列文章Cilium系列文章前言今天我们进入Cilium安全相关主题,介绍Kubernetes网络策略以及CiliumNetworkPolicies额外支持的内容。网络策略(NetworkPolicy)的类型默认情况下,Kubernetes集群中的所有pod都可被其他pod和网络端点访问。网络策略允许用户定义Kuber......
  • Cilium系列-14-Cilium NetworkPolicy 简介
    系列文章Cilium系列文章前言今天我们进入Cilium安全相关主题,介绍Kubernetes网络策略以及CiliumNetworkPolicies额外支持的内容。网络策略(NetworkPolicy)的类型默认情况下,Kubernetes集群中的所有pod都可被其他pod和网络端点访问。网络策略允许用户定义Kube......
  • 开源.NetCore通用工具库Xmtool使用连载 - XML操作篇
    【Github源码】《上一篇》介绍了Xmtool工具库中的发送短信类库,今天我们继续为大家介绍其中的XML操作类库。XML操作是软件开发过程中经常会遇到的情况;包括XML内容的遍历解析,或者特定值内容的查询获取等等。Xmtool工具库提供了一种更方便的方式对Xml进行遍历解析或者对特定节点......
  • .Net Web API 005 Controller上传小文件
    1、附属文件对象定义一般情况下,系统里面的文件都会附属一个对象存在,例如用户的头像文件,会附属用户对象存在。邮件中的文件会附属邮件存在。所以在系统里面,我们会创建一个附属文件对象,命名为AttachedFileEntity。其定义如下所示。///<summary>///附属文件实体对象///</summ......
  • Scientific Internet Surfing
    1.Background作为一名烟酒生不管是学习还是那啥都需要一些国外的资源,在windows和安卓平台上都可以找到很多好用的加速器,比如liebao加速器(我本人只用过这个),还有一些博客会推荐Nord或者Express(但是访问不了)博客地址虽然要付费吧,但是物有所值,总归是能解决问题,可是这事放到li......
  • 将 SmartAssembly 与单文件可执行文件一起使用 (.NET Core 6)
    合集-.net代码混淆加密产权保护(3) 1.记一次.net加密神器Eazfuscator.NET2023.2最新版使用尝试06-272.将SmartAssembly与单文件可执行文件一起使用(.NETCore6)06-273.【干货】浅谈如何给.net程序加多层壳达到1+1>2的效果08-05收起 .NETCore6引入了创建......
  • 浅谈如何给.net程序加多层壳达到1+1>2的效果
    合集-.net代码混淆加密产权保护(3) 1.记一次.net加密神器Eazfuscator.NET2023.2最新版使用尝试06-272.将SmartAssembly与单文件可执行文件一起使用(.NETCore6)06-273.【干货】浅谈如何给.net程序加多层壳达到1+1>2的效果08-05收起 软件破解分白盒和......
  • .NET 个人博客-首页排版优化-2
    个人博客-首页排版优化-2原本这篇文章早就要出了的,结果之前买的服务器服务商跑路了,导致博客的数据缺失了部分。我是买了一年的服务器,然后用了3个月,国内跑路云太多了,然后也是花钱重新去别的服务商买了一台服务器,这次只买了一个月,先试试水。优化计划置顶3个且可滚动或切换推......
  • Kubernetes中的ingress问题
    大佬们想问一下我这个问题该如何解决啊,ip访问没问题,但是域名就有问题了     ......