深入剖析 ET8 框架的 Fiber 机制:一个纤程的诞生、心跳、传信与消亡

56 阅读15分钟

深入剖析 ET8 框架的 Fiber 机制

引言:为什么从 Fiber 开始读 ET8

也是偶然间重新审视 ET(一款双端通用的游戏开发框架),惊艳于它 8.x 版本重构后的轻与净——客户端与服务端共享同一套代码,进程内又能同时跑着成百上千个彼此隔离的逻辑单元。按捺不住对源码的探索欲,便构思着分模块、按链路地去挖掘它的设计思路。这个系列剖析基于的源码版本是 ET release 8.1。

整个 ET8 的架构是层层递进的:Process → Fiber → Scene → Entity → Component → System。如果 Entity 是"细胞",那么 Fiber 就是"器官"——ETTask 的 await 靠它回家,Entity 树长在它的 Root Scene 上,Actor 消息穿过它的队列,网络回调落在它的信箱里。不先把 Fiber 读透,后面每一层都是空中楼阁,所以系列的第一篇,主抓 Fiber。

本文围绕四条完整链路展开:创建、调度、通信、销毁。核心类登场时会先完整展示整个类的源码,再逐段解剖,每一行核心代码都会给出解释,以此揭示 ET8 如何用"队列串行化"替代"锁",如何在单线程语义下支撑高并发,以及如何在编译期硬性保证 Fiber 之间的隔离。

阅读约定:文中所有完整类源码的区块注释(// ─── xxx ───)是为阅读体验添加的,非源码原有;行号与 release 8.1 一致。文件路径均相对 Unity/Assets/Scripts/。

设计概览:Fiber 的整体架构与组件图谱

Fiber 在进程中的位置

ET8 把一个进程拆成三层:

Process(进程,全局唯一进程号)
  └── Fiber(纤程,进程内调度单元,有独立 Id)
        └── Root Scene(根场景,一棵 Entity 树的根)
              └── Entity / Component / 子 Scene...

为什么需要 Fiber 这一层?传统多线程的答案是"共享内存 + 锁",而 ET8 的答案是**"把线程变细,细到不需要锁":每个 Fiber 在逻辑上只有一个执行者(一个独占线程,或主线程上的一段独占时间片),它内部的全部代码都是单线程语义——不用锁、不用原子操作、不用考虑竞争;Fiber 之间则禁止共享引用**,一切协作通过消息完成。这本质上是一套运行时的 Actor 模型,Fiber 就是 Actor 的"居所"。

核心组件关系图谱

从代码结构来看,Fiber 机制的核心组件可归纳为五类:

  • 管理层:FiberManager(单例)持有全进程 Fiber 注册表,负责创建与销毁,并按 SchedulerType 把 Fiber 分派给对应调度器。
  • 调度层:IScheduler 接口 + 三个实现——MainThreadScheduler(主线程轮转)、ThreadScheduler(一 Fiber 一线程)、ThreadPoolScheduler(M 线程跑 N Fiber)。
  • 执行层:Fiber 本体,携带 EntitySystem、Mailboxes、ThreadSynchronizationContext、Log 四大器官,以及 Root Scene。
  • 回调层:ThreadSynchronizationContext——每个 Fiber 一个的 ConcurrentQueue<Action>,跨线程回调的唯一落地处。
  • 通信层:进程级单例 MessageQueue(FiberId → 消息队列的字典)+ Fiber 级的 ProcessInnerSender 与 Mailboxes,构成进程内跨 Fiber 的邮路。

四条链路一览

这些组件的协作可以概括为四条链路:

创建:FiberManager.Create → new Fiber(纯内存,不起线程)→ 注册进字典 → 调度器缓冲 → Post 初始化回调进 Fiber 自己的 ThreadSynchronizationContext → 下一帧心跳时执行初始化 → 返回 fiberId

心跳:进程主循环 → FiberManager.Update/LateUpdate → 调度器轮转 → 双设置(立身份)→ fiber.Update/LateUpdate → 排空 Fiber 的 ThreadSynchronizationContext

传信:Call 分配 RpcId → 消息入 MessageQueue 中目标 Fiber 的队列 → 目标 Fiber 下一帧 Fetch(限量 1000)→ 响应走唤醒捷径 / 普通消息投给 MailBoxComponent → SetResult 唤醒发起方

销毁:Remove 把销毁动作 Post 进目标 Fiber 的 ThreadSynchronizationContext → Fiber 在自己线程上死去 → 调度器通过轮询观察到死亡 → 队列自然淘汰

全文涉及的类共 11 个,按链路登场顺序:链路一读 FiberManager 与 Fiber;链路二读三个调度器与 ThreadSynchronizationContext;链路三读 ProcessInnerSender、MessageQueue、MailBoxComponent、Mailboxes 与几个关键数据结构;链路四回收伏笔。每个类先全貌、后解剖。


链路一:诞生——FiberManager 是纤程世界的"户籍管理处"

1.1 FiberManager 全貌

源码位于 Core/World/Module/Fiber/FiberManager.cs,全文件 135 行。它是 Fiber 机制的管理中枢:一个进程只有一个 FiberManager 单例(继承 Singleton<FiberManager>,实现 ISingletonAwake 启动装配、ISingletonReverseDispose 控制销毁顺序),下辖 Fiber 注册表、id 生成器与三个调度器。

using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;

namespace ET
{
    // ─── 调度类型枚举 ───
    public enum SchedulerType
    {
        Main,
        Thread,
        ThreadPool,
    }

    // ─── 管理中枢:进程内唯一单例 ───
    public class FiberManager: Singleton<FiberManager>, ISingletonAwake, ISingletonReverseDispose
    {
        private readonly IScheduler[] schedulers = new IScheduler[3];

        private int idGenerator = 10000000; // 10000000以下为保留的用于StartSceneConfig的fiber id, 1个区配置1000个纤程,可以配置10000个区
        private ConcurrentDictionary<int, Fiber> fibers = new();

        private MainThreadScheduler mainThreadScheduler;

        // ─── 单例唤醒:装配三种调度器 ───
        public void Awake()
        {
            this.mainThreadScheduler = new MainThreadScheduler(this);
            this.schedulers[(int)SchedulerType.Main] = this.mainThreadScheduler;

#if ENABLE_VIEW && UNITY_EDITOR
            this.schedulers[(int)SchedulerType.Thread] = this.mainThreadScheduler;
            this.schedulers[(int)SchedulerType.ThreadPool] = this.mainThreadScheduler;
#else
            this.schedulers[(int)SchedulerType.Thread] = new ThreadScheduler(this);
            this.schedulers[(int)SchedulerType.ThreadPool] = new ThreadPoolScheduler(this);
#endif
        }

        // ─── 每帧驱动(仅主线程调度器需要) ───
        public void Update()
        {
            this.mainThreadScheduler.Update();
        }

        public void LateUpdate()
        {
            this.mainThreadScheduler.LateUpdate();
        }

        // ─── 进程退出:先停调度器,再销毁Fiber ───
        protected override void Destroy()
        {
            foreach (IScheduler scheduler in this.schedulers)
            {
                scheduler.Dispose();
            }

            foreach (var kv in this.fibers)
            {
                kv.Value.Dispose();
            }

            this.fibers = null;
        }

        // ─── 创建Fiber主重载 ───
        public async ETTask<int> Create(SchedulerType schedulerType, int fiberId, int zone, SceneType sceneType, string name)
        {
            try
            {
                Fiber fiber = new(fiberId, zone, sceneType, name);

                if (!this.fibers.TryAdd(fiberId, fiber))
                {
                    throw new Exception($"same fiber already existed, if you remove, please await Remove then Create fiber! {fiberId}");
                }
                this.schedulers[(int) schedulerType].Add(fiberId);

                TaskCompletionSource<bool> tcs = new TaskCompletionSource<bool>();

                fiber.ThreadSynchronizationContext.Post(async () =>
                {
                    try
                    {
                        // 根据Fiber的SceneType分发Init,必须在Fiber线程中执行
                        await EventSystem.Instance.Invoke<FiberInit, ETTask>((long)sceneType, new FiberInit() {Fiber = fiber});
                        tcs.SetResult(true);
                    }
                    catch (Exception e)
                    {
                        Log.Error($"init fiber fail: {sceneType} {e}");
                    }
                });

                await tcs.Task;
                return fiberId;
            }
            catch (Exception e)
            {
                throw new Exception($"create fiber error: {fiberId} {sceneType}", e);
            }
        }

        // ─── 创建Fiber:动态分配Id ───
        public async ETTask<int> Create(SchedulerType schedulerType, int zone, SceneType sceneType, string name)
        {
            int fiberId = Interlocked.Increment(ref this.idGenerator);
            return await this.Create(schedulerType, fiberId, zone, sceneType, name);
        }

        // ─── 销毁Fiber ───
        public async ETTask Remove(int id)
        {
            Fiber fiber = this.Get(id);
            TaskCompletionSource<bool> tcs = new();
            // 要扔到fiber线程执行,否则会出现线程竞争
            fiber.ThreadSynchronizationContext.Post(() =>
            {
                if (this.fibers.Remove(id, out Fiber f))
                {
                    f.Dispose();
                }
                tcs.SetResult(true);
            });
            await tcs.Task;
        }

        // ─── 内部获取:隔离性的最后一道闸 ───
        // 不允许外部调用,容易出现多线程问题, 只能通过消息通信,不允许直接获取其它Fiber引用
        internal Fiber Get(int id)
        {
            this.fibers.TryGetValue(id, out Fiber fiber);
            return fiber;
        }

        // ─── 存活计数:线程池调度算配额用 ───
        public int Count()
        {
            return this.fibers.Count;
        }
    }
}

一眼望去,这个类的骨架非常干净:字段区(第 18-23 行)只有三个成员;生命周期区(第 25-62 行)负责装配、驱动与销毁;业务区(第 64-133 行)就是三对方法——Create 两个重载、Remove、Get、Count。下面我们沿着创建链路逐段解剖。

1.2 逐段解剖:Create 的前三步

先看动态分配 Id 的重载(第 101-105 行):

public async ETTask<int> Create(SchedulerType schedulerType, int zone, SceneType sceneType, string name)
{
    int fiberId = Interlocked.Increment(ref this.idGenerator);
    return await this.Create(schedulerType, fiberId, zone, sceneType, name);
}
  • Interlocked.Increment:id 自增是整个进程内多线程并发创建 Fiber 时唯一的共享变量写操作,用一个原子指令保护,除此之外再无锁;
  • idGenerator 从 10000000 起步,源码注释(第 20 行)写明了原因:10000000以下为保留的用于StartSceneConfig的fiber id, 1个区配置1000个纤程,可以配置10000个区——配置表里的静态 Fiber(各类进程 Scene)用一千万以下的小 Id,运行时动态创建用一千万以上的大 Id,两套编号互不冲突,各取所需。

进入四参主重载(第 64-99 行),第一步:

Fiber fiber = new(fiberId, zone, sceneType, name);

构造器位于 Core/Fiber/Fiber.cs 第 54-67 行——它是理解 Fiber "器官构成"的最佳入口,我们马上会完整展示这个类。此刻只需记住:这是纯内存操作,不启动任何线程。

第二步,注册(第 70-73 行):

if (!this.fibers.TryAdd(fiberId, fiber))
{
    throw new Exception($"same fiber already existed, if you remove, please await Remove then Create fiber! {fiberId}");
}

fibers(第 21 行声明)是 ConcurrentDictionary<int, Fiber>——创建与移除可能发生在不同线程。TryAdd 失败的报错文案本身就是一条使用规约:必须先 await Remove 完成,再 Create 同 Id 的 Fiber,因为此刻旧 Fiber 可能还活在某个线程里,同 Id 共存会引发消息错投。先注册进字典、再交给调度器,顺序也不可颠倒——顺序错了,调度器线程会 Get(fiberId) 拿到 null。

第三步,交给调度器(第 74 行):

this.schedulers[(int) schedulerType].Add(fiberId);

很多读者第一次读这行会误会:以为 Add 是往 schedulers 数组里塞东西。注意这是索引取值 + 对象方法的两步——this.schedulers[(int)schedulerType] 按枚举值取出的是调度器对象(第 25-37 行 Awake 装配时放进去的),.Add(fiberId) 是 IScheduler 接口的唯一方法:

// Core/World/Module/Fiber/IScheduler.cs,全文 9 行
public interface IScheduler: IDisposable
{
    void Add(int fiberId);
}

同一个 Add(fiberId),三个调度器各有各的实现:

调度器Add(fiberId) 的实现含义
MainThreadScheduler进 addIds 缓冲队列,等帧末转正下一节详述
ThreadSchedulernew Thread(() => Loop(fiberId)).Start()立刻开一条线程跑这个 Fiber
ThreadPoolScheduler进 idQueue 共享队列等工作线程领取

FiberManager 不关心这些细节——它只发一句"这个 fiberId 交给你了",怎么驱动是调度器自己的事。这就是经典的策略模式:FiberManager 是上下文,IScheduler 是策略。还有一个值得品的设计点:传的是 fiberId 而不是 Fiber 对象。如果调度器直接持有 Fiber 引用,Remove 之后还得逐个通知调度器"别驱动它了";现在调度器只认 id,每次驱动前用 Get(fiberId) 反查一次——查得到且没 disposed 才驱动。持 id 反查让"死亡发现"变成调度器每轮自查的事,这正是链路四"死亡信息通过共享字典 + 每轮轮询传播"的实现基础。

1.3 逐段解剖:Post 初始化——创建链路的灵魂

第 76-93 行是整条创建链路的灵魂:

TaskCompletionSource<bool> tcs = new TaskCompletionSource<bool>();

fiber.ThreadSynchronizationContext.Post(async () =>
{
    try
    {
        // 根据Fiber的SceneType分发Init,必须在Fiber线程中执行
        await EventSystem.Instance.Invoke<FiberInit, ETTask>((long)sceneType, new FiberInit() {Fiber = fiber});
        tcs.SetResult(true);
    }
    catch (Exception e)
    {
        Log.Error($"init fiber fail: {sceneType} {e}");
    }
});

await tcs.Task;
return fiberId;

逐层拆解:

  • 初始化不是直接调用,而是被 Post 进了这个 Fiber 自己的 ThreadSynchronizationContext。原代码注释(第 82 行)点明了原因——必须在Fiber线程中执行。为什么?初始化要 new 一堆 Entity、挂一堆组件、await 网络请求,这些操作都依赖"当前线程 == 本 Fiber 的线程"这个前提(Fiber.Instance、Entity.IScene 缓存、await 续体的上下文,全都是在 Fiber 线程内才成立的)。在哪个线程调用了 Create 并不重要——调用方可能是另一个 Fiber,可能是线程池——重要的是初始化必须发生在目标 Fiber 的"领地"之内;
  • EventSystem.Instance.Invoke<FiberInit, ETTask>((long)sceneType, ...):按 SceneType 分发。EventSystem.Invoke<A, T>(long type, A args) 的实现(Core/World/Module/EventSystem/EventSystem.cs:174)是一个两级字典查找:allInvokers[typeof(A)][type]——先按参数类型、再按 long 键,找到 [Invoke] 特性标记的处理器。这套分发机制的全貌属于系列第四篇,这里只需建立直觉:给一把 long 钥匙,EventSystem 替你找到对应的处理器类。
  • FiberInit 只是个包装结构(Core/World/Module/Fiber/FiberInit.cs 全文 8 行:public struct FiberInit { public Fiber Fiber { get; set; } }),真正的初始化逻辑在热更层,每种 SceneType 注册一个 [Invoke] 处理器。看一个典型的,Hotfix/Share/FiberInit_Main.cs:
[Invoke((long)SceneType.Main)]
public class FiberInit_Main: AInvokeHandler<FiberInit, ETTask>
{
    public override async ETTask Handle(FiberInit fiberInit)
    {
        Scene root = fiberInit.Fiber.Root;
        await EventSystem.Instance.PublishAsync(root, new EntryEvent1());
        await EventSystem.Instance.PublishAsync(root, new EntryEvent2());
        await EventSystem.Instance.PublishAsync(root, new EntryEvent3());
    }
}

Router、NetInner、Location、RoomRoot、Map……十几种 SceneType 各有自己的 FiberInit_* 处理器。Main 的初始化是往根 Scene 上发三轮事件 EntryEvent1/2/3——三轮启动事件是 ET 的约定,业务层各自订阅挂组件。注意处理器内部全是 await:加载配置、连数据库、起网络服务都在这些事件的处理器里异步完成;

  • tcs.SetResult(true) 位于 await 完成之后——所以 Create 的返回时刻是"该 Fiber 的初始化异步逻辑全部跑完"的时刻,而不是"回调入队"的时刻。对调用方来说,拿到 fiberId 就意味着这个 Fiber 已经可以接客了;
  • 最外层 await tcs.Task:调用 Create 的可能是另一个 Fiber(Fiber 之间通过消息协作,"创建 Fiber"本身就是一条可异步等待的指令),TCS 把"跨线程的完成通知"桥接成 ETTask,整个 Create 呈现为一个可 await 的普通异步方法;
  • 注意异常路径(第 86-89 行):初始化失败只打日志、不 SetResult——await tcs.Task 将永远挂起。这是刻意的 fail-stop:初始化失败的 Fiber 不允许"假装创建成功",上层只能靠超时感知,宁挂不骗。

链路的调度侧:Post 进 ThreadSynchronizationContext 的回调由谁执行?先把时序结论放在这:Main 调度模式下,新 Fiber 在第 N 帧 LateUpdate 才从缓冲并入正式轮转队列,第 N+1 帧第一次被 Update,第 N+1 帧的 LateUpdate 才消费到这条初始化回调。时序的正确性完全由"入队位置"保证——这是 ET8 调度手法里最值得品味的一笔,进入链路二详述。

动手验证①:在 FiberInit_Main.Handle 第一行打断点,在 Create 的 await tcs.Task 处也打一个。启动客户端观察:初始化断点命中的线程是主线程,且晚于 new Fiber 一两帧——"Post 进队列、等心跳消费"的时序眼见为实。再把 Handle 里第一个 await 改成 await TimerComponent.Instance.WaitAsync(5000),会发现 Create 的返回也推迟了 5 秒:Create 等的是初始化的全部完成,不是入队。

1.4 Fiber 全貌:纤程本体的四大器官

源码位于 Core/Fiber/Fiber.cs,全文件 123 行。如果说 FiberManager 是户籍管理处,Fiber 就是落户口的"市民"——它的一切生理结构都在这个类里。

using System;
using System.Collections.Generic;
using System.Threading;

namespace ET
{
    // ─── 扩展助手:任何Entity都能拿到自己的ActorId门牌 ───
    public static class FiberHelper
    {
        public static ActorId GetActorId(this Entity self)
        {
            Fiber root = self.Fiber();
            return new ActorId(root.Process, root.Id, self.InstanceId);
        }
    }

    public class Fiber: IDisposable
    {
        // ─── 线程身份:全框架最精妙的单行代码之一 ───
        // 该字段只能框架使用,绝对不能改成public,改了后果自负
        [StaticField]
        [ThreadStatic]
        internal static Fiber Instance;

        // ─── 基础状态 ───
        public bool IsDisposed;

        public int Id;

        public int Zone;

        public Scene Root { get; }

        // ─── 地址与进程号 ───
        public Address Address
        {
            get
            {
                return new Address(this.Process, this.Id);
            }
        }

        public int Process
        {
            get
            {
                return Options.Instance.Process;
            }
        }

        // ─── 四大器官 ───
        public EntitySystem EntitySystem { get; }
        public Mailboxes Mailboxes { get; private set; }
        public ThreadSynchronizationContext ThreadSynchronizationContext { get; }
        public ILog Log { get; }

        private readonly Queue<ETTask> frameFinishTasks = new();

        // ─── 构造:纯内存,不起线程 ───
        internal Fiber(int id, int zone, SceneType sceneType, string name)
        {
            this.Id = id;
            this.Zone = zone;
            this.EntitySystem = new EntitySystem();
            this.Mailboxes = new Mailboxes();
            this.ThreadSynchronizationContext = new ThreadSynchronizationContext();
#if UNITY
            this.Log = Logger.Instance.Log;
#else
            this.Log = new NLogger(sceneType.ToString(), this.Process, this.Id);
#endif
            this.Root = new Scene(this, id, 1, sceneType, name);
        }

        // ─── 每帧两拍 ───
        internal void Update()
        {
            try
            {
                this.EntitySystem.Update();
            }
            catch (Exception e)
            {
                this.Log.Error(e);
            }
        }

        internal void LateUpdate()
        {
            try
            {
                this.EntitySystem.LateUpdate();
                FrameFinishUpdate();

                this.ThreadSynchronizationContext.Update();
            }
            catch (Exception e)
            {
                Log.Error(e);
            }
        }

        // ─── 等当前帧结束 ───
        public async ETTask WaitFrameFinish()
        {
            ETTask task = ETTask.Create(true);
            this.frameFinishTasks.Enqueue(task);
            await task;
        }

        private void FrameFinishUpdate()
        {
            while (this.frameFinishTasks.Count > 0)
            {
                ETTask task = this.frameFinishTasks.Dequeue();
                task.SetResult();
            }
        }

        // ─── 销毁 ───
        public void Dispose()
        {
            if (this.IsDisposed)
            {
                return;
            }
            this.IsDisposed = true;

            this.Root.Dispose();
        }
    }
}

第 18-21 行是全 ET8 最精妙的单行代码之一,逐行看这三个标记:

  • [ThreadStatic](第 20 行):每个物理线程一份独立存储。先看没有这个特性会怎样——普通 static 字段全进程只有一份,主线程轮转时 Fiber A 刚把 Instance = A,轮到 Fiber B 时被改成 B,若 A 的某个回调此刻正在别的线程跑,它读到的"自己"就面目全非了。"我是谁"必须跟执行者线程走,而不是跟进程走——这就是 [ThreadStatic] 存在的理由。调度器在调用 fiber.Update() 之前先 Fiber.Instance = fiber,执行完再置空,于是任何代码、任何调用深度下都能凭它回答"我是谁";
  • [StaticField](第 19 行):ET 静态分析约束(Analyzer 项目中的诊断规则),防止静态字段被滥用导致内存泄漏与多线程问题;
  • internal + 第 18 行的注释"该字段只能框架使用,绝对不能改成public,改了后果自负":外部拿不到这个字段,就无法绕过消息机制直接操纵别的 Fiber——这是 Actor 隔离性的硬性保证。

第 47-50 行的四大器官正好对应 Fiber 的四大职责:

成员职责本文哪节展开
EntitySystem驱动挂在这个 Fiber 下的所有组件 System 的 Update链路二(2.3 节)
Mailboxes本 Fiber 内所有 Actor 的注册表链路三(3.5 节)
ThreadSynchronizationContext本 Fiber 的同步上下文——所有跨线程回调在此排队链路二(2.4 节)
Log独立日志通道(服务端按 场景类型_进程号_FiberId 命名)——

第 31-45 行的两个属性配件:Address = 进程内地址(进程号 + FiberId),是 MessageQueue 寻址的键;Process 不存字段、直接读全局配置——同一进程内所有 Fiber 的进程号必然相同,没必要每个 Fiber 记一份冗余。

第 54-67 行的构造函数,承接 1.2 节 new Fiber(...) 那句:

  • 纯内存操作,不启动任何线程——Fiber 的"线程"不属于自己,是调度器借给它的;
  • 构造器是 internal:Fiber 只能由 FiberManager 创建,业务代码连 new 都写不出来,隔离性从构造一刻就立下了;
  • 服务端分支 new NLogger(sceneType.ToString(), this.Process, this.Id)——一个进程几千个 Fiber,日志按进程号和 FiberId 命名,排障时能直接过滤出某个 Fiber 的完整生命周期;
  • Root = new Scene(this, id, 1, ...)(第 66 行):一个 Fiber 一棵 Entity 树,树根的实例 Id 固定为 1,Fiber 内部编号自洽,全局唯一性由 Fiber.Id 补齐。

第 7-14 行的 FiberHelper 是 ActorId 门牌号的生成处:任何 Entity 都能用 root.Process + root.Id + self.InstanceId 三元组拼出自己的全局地址。这个三元组不是随手拼的,它就是 ActorId 结构体的字段构成——链路三 3.1 节会给出它的完整定义。

第 112-121 行的 Dispose 极简:幂等保护 + 置标志 + 从根 Scene 级联销毁整棵 Entity 树。它在链路四由 Remove 触发。

至于第 69-110 行的每帧两拍与等帧末小链路,正是链路二的主角——但讲它们之前,得先看看 Fiber 是被谁、以什么方式唤醒的。


链路二:心跳——调度器是纤程的"起搏器"

2.0 调度层的装配与总开关

回到 FiberManager.cs 第 39-47 行,单例每帧被进程主循环驱动(Unity 侧由 GameLoop 调用,服务端 DotNet/Loader/Init.cs 的主循环同样调用):

public void Update()
{
    this.mainThreadScheduler.Update();
}

public void LateUpdate()
{
    this.mainThreadScheduler.LateUpdate();
}

注意:只有主线程调度器有 Update/LateUpdate 入口——Thread 和 ThreadPool 调度器旗下的 Fiber 由各自线程驱动,无需外部推。三种调度器在第 25-37 行的 Awake() 里完成装配,ENABLE_VIEW 分支上文已述。

2.1 MainThreadScheduler 全貌:客户端 Fiber 的家

源码位于 Core/World/Module/Fiber/MainThreadScheduler.cs,全文件 107 行。Unity 客户端上所有 Fiber 都住在这里。

using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Threading;

namespace ET
{
    internal class MainThreadScheduler: IScheduler
    {
        // ─── 两个队列:addIds是缓冲,idQueue是轮转 ───
        private readonly ConcurrentQueue<int> idQueue = new();
        private readonly ConcurrentQueue<int> addIds = new();
        private readonly FiberManager fiberManager;
        private readonly ThreadSynchronizationContext threadSynchronizationContext = new();

        // ─── 构造:主线程一启动就被纳入ET的上下文体系 ───
        public MainThreadScheduler(FiberManager fiberManager)
        {
            SynchronizationContext.SetSynchronizationContext(this.threadSynchronizationContext);
            this.fiberManager = fiberManager;
        }

        public void Dispose()
        {
            this.addIds.Clear();
            this.idQueue.Clear();
        }

        // ─── 每帧Update:先清无主回调,再轮转所有Fiber ───
        public void Update()
        {
            SynchronizationContext.SetSynchronizationContext(this.threadSynchronizationContext);
            this.threadSynchronizationContext.Update();

            int count = this.idQueue.Count;
            while (count-- > 0)
            {
                if (!this.idQueue.TryDequeue(out int id))
                {
                    continue;
                }

                Fiber fiber = this.fiberManager.Get(id);
                if (fiber == null)
                {
                    continue;
                }

                if (fiber.IsDisposed)
                {
                    continue;
                }

                Fiber.Instance = fiber;
                SynchronizationContext.SetSynchronizationContext(fiber.ThreadSynchronizationContext);
                fiber.Update();
                Fiber.Instance = null;

                this.idQueue.Enqueue(id);
            }

            // Fiber调度完成,要还原成默认的上下文,否则unity的回调会找不到正确的上下文
            SynchronizationContext.SetSynchronizationContext(this.threadSynchronizationContext);
        }

        // ─── 每帧LateUpdate:Fiber的LateUpdate + 新兵转正 ───
        public void LateUpdate()
        {
            int count = this.idQueue.Count;
            while (count-- > 0)
            {
                if (!this.idQueue.TryDequeue(out int id))
                {
                    continue;
                }

                Fiber fiber = this.fiberManager.Get(id);
                if (fiber == null)
                {
                    continue;
                }

                if (fiber.IsDisposed)
                {
                    continue;
                }

                Fiber.Instance = fiber;
                SynchronizationContext.SetSynchronizationContext(fiber.ThreadSynchronizationContext);
                fiber.LateUpdate();
                Fiber.Instance = null;

                this.idQueue.Enqueue(id);
            }

            while (this.addIds.Count > 0)
            {
                this.addIds.TryDequeue(out int result);
                this.idQueue.Enqueue(result);
            }

            // Fiber调度完成,要还原成默认的上下文,否则unity的回调会找不到正确的上下文
            SynchronizationContext.SetSynchronizationContext(this.threadSynchronizationContext);
        }

        // ─── 入伍只是进缓冲,要等帧末才转正 ───
        public void Add(int fiberId = 0)
        {
            this.addIds.Enqueue(fiberId);
        }
    }
}

类的骨架先看懂:第 9-10 行两个队列是全文最关键的伏笔——addIds 是缓冲,idQueue 是正式轮转队列。第 14-18 行的构造函数就做了一次 SetSynchronizationContext,主线程一启动即被纳入 ET 的上下文体系。

2.2 Update 逐段解剖:轮转五行,密度最高

第 26-29 行,帧首两件事:

SynchronizationContext.SetSynchronizationContext(this.threadSynchronizationContext);
this.threadSynchronizationContext.Update();

把调度器自己的同步上下文设为当前线程上下文,然后把它排空。谁会 Post 到这里?不隶属任何 Fiber 的主线程回调(Unity 引擎触发的、跨线程的兜底投递等)。先把"无主回调"清掉,再进 Fiber 轮转。

第 31-49 行,快照轮转:

int count = this.idQueue.Count;
while (count-- > 0)
{
    if (!this.idQueue.TryDequeue(out int id))
    {
        continue;
    }

    Fiber fiber = this.fiberManager.Get(id);
    if (fiber == null)
    {
        continue;
    }

    if (fiber.IsDisposed)
    {
        continue;
    }

count 取循环开始那一刻的队列长度,本轮只执行快照内的 Fiber,执行完逐一塞回队尾——于是本帧新加入的 Fiber 不会插队,一帧之内每个存活的 Fiber 恰好被唤醒一次,数学上严格的公平。代入一个具体场景演算一遍:

时刻idQueue 状态发生的事件
第 N 帧 Update 开始[A, B, C]count = 3,快照锁定
处理 A[B, C] → [B, C, A]A 执行完回队尾
处理 B、C[A, B, C]依次执行回队尾
期间有人 Create(D)[A, B, C](不变)D 只进了 addIds,不碰 idQueue
第 N 帧 LateUpdate[A, B, C] → 轮转后 [A, B, C]然后把 addIds 里的 D 并入 → [A, B, C, D]
第 N+1 帧 Update[A, B, C, D]D 才第一次被执行

Get(id) 返回 null(Fiber 已被 Remove)或 IsDisposed(Fiber 已自杀)时直接 continue——关键:这两个分支都不执行第 55 行的 Enqueue(id),死亡的 Fiber 出队后不再回队,从轮转里自然淘汰。消亡的清理不需要任何主动摘除动作,这个伏笔在链路四回收。

第 50-55 行,轮转体只有五行,是整个 ET8 线程模型密度最高的五行:

Fiber.Instance = fiber;
SynchronizationContext.SetSynchronizationContext(fiber.ThreadSynchronizationContext);
fiber.Update();
Fiber.Instance = null;

this.idQueue.Enqueue(id);

这就是双设置(Fiber.Instance = fiber + SetSynchronizationContext),缺一不可,各做一个反例推演:

  • Fiber.Instance = fiber:Fiber.cs 第 19-21 行那个 [ThreadStatic] 字段此刻被赋值。从这一行到 Fiber.Instance = null 之间,当前线程就是该 Fiber 的专属线程。若只有这一行没有下一行:Entity.Fiber() 能找到 Fiber,但任何 await 的续体将失去归途——.NET 找不到 SynchronizationContext,默认把续体扔进线程池。网络响应回来时,你的业务代码跑在某个池线程上,Fiber.Instance 是 null,Entity.Fiber() 找不到归属、Post 排不进队列——Fiber 世界的一切身份设施全部失效;
  • SetSynchronizationContext(...):若只有这一行没有 Fiber.Instance:await 续体倒是能正确回家了,但代码里所有凭 Fiber.Instance 找组织的设施(ActorId 生成、跨 Fiber 发送入口)全部失明。前者是"回家地址",后者是"工作牌"——调度器进门前两个都得办;
  • Fiber.Instance = null:用完即清。防御性写法——若有代码把 Fiber 上下文偷偷逃逸到帧外(比如把 Fiber.Instance 存进静态字段),null 能立刻暴露问题而不是静默错绑;
  • Enqueue(id):活着才回队尾,与前面的死亡分支形成闭环。

第 58-59 行帧末还原,注释已自明:Unity 引擎自己的回调(UI 事件、协程、渲染回调)发生在 Fiber 轮转之外,它们看到的必须是调度器那个"无主"默认上下文。

2.3 Fiber 的每帧两拍与"等帧末"小链路

现在可以看 Fiber.cs 第 69-94 行的两拍:

internal void Update()
{
    try
    {
        this.EntitySystem.Update();
    }
    catch (Exception e)
    {
        this.Log.Error(e);
    }
}

单线程不等于不出异常。一个 Fiber 的 Update 抛异常,只死它自己这一帧,try-catch 兜住、记入本 Fiber 的日志,调度器继续转下一个 Fiber——一个 Fiber 的 bug 不会拖垮整个进程。

internal void LateUpdate()
{
    try
    {
        this.EntitySystem.LateUpdate();
        FrameFinishUpdate();

        this.ThreadSynchronizationContext.Update();
    }
    catch (Exception e)
    {
        Log.Error(e);
    }
}

三步的顺序本身就是设计:先跑业务 LateUpdate,再唤醒等帧末的人,最后消费跨线程回调。

这里必须回答一个读者必然会问的问题:EntitySystem.Update() 到底在驱动什么? 以 ProcessInnerSender.Update 为例——它明明只是个静态方法,怎么做到"每帧被调用"的?答案藏在三个环节的配合下(完整机制属于系列第四篇,这里建立链条直觉):

  1. ProcessInnerSender 实体类声明了 IUpdate 接口(Core/Fiber/Module/Actor/ProcessInnerSender.cs:6:public class ProcessInnerSender: Entity, IAwake, IDestroy, IUpdate);
  2. 组件挂上 Scene 时,EntitySystem.RegisterSystem 把它登记进 Update 队列(Core/Fiber/EntitySystem.cs:19-36,按该类型的 QueueFlag 入队);
  3. 每帧 Fiber.Update() → EntitySystem.Update() 快照遍历这个队列,对存活组件逐一调用其 System 的 [EntitySystem] Update 方法(EntitySystem.cs:38-88)。

贴出 EntitySystem.Update 的完整实现,你会看到一个熟悉的身影:

// Core/Fiber/EntitySystem.cs 第 38-88 行(LateUpdate 同构,第 90-132 行)
public void Update()
{
    Queue<EntityRef<Entity>> queue = this.queues[InstanceQueueIndex.Update];
    int count = queue.Count;
    while (count-- > 0)
    {
        Entity component = queue.Dequeue();
        // ... null / IsDisposed / IUpdate 检查 ...
        queue.Enqueue(component);
        foreach (IUpdateSystem iUpdateSystem in iUpdateSystems)
        {
            iUpdateSystem.Run(component);
        }
    }
}

count = queue.Count; while(count-- > 0) 出队执行回队尾——和调度器轮转 Fiber 是同一个手法。这个"快照轮转"在 ET8 里反复出现:调度器用它轮转 Fiber,EntitySystem 用它轮转组件。一个手法,两个尺度,这是 ET8 代码统一性的最佳佐证。

夹在中间的小链路顺手讲完,Fiber.cs 第 96-110 行:

public async ETTask WaitFrameFinish()
{
    ETTask task = ETTask.Create(true);
    this.frameFinishTasks.Enqueue(task);
    await task;
}

这行 ETTask.Create(true) 值得停一下:查 ETTask.cs 第 30-41 行,Create(bool fromPool = false) 的参数含义是**"是否从对象池取"**——true 表示复用池化的 ETTask 实例。WaitFrameFinish 是每帧高频调用,池化省去反复分配。源码注释里有个警告值得一起读:"假如开启了池, await 之后不能再操作 ETTask,否则可能操作到再次从池中分配出来的 ETTask"——本处的用法恰好合规:入队、await、之后再也不碰它。

private void FrameFinishUpdate()
{
    while (this.frameFinishTasks.Count > 0)
    {
        ETTask task = this.frameFinishTasks.Dequeue();
        task.SetResult();
    }
}

FrameFinishUpdate 在帧末统一 SetResult 唤醒。为什么必须放在"业务 LateUpdate 之后、回调消费之前"?因为等帧末的人(帧同步、渲染收集)要看到的是一个业务已尘埃落定、回调尚未搅局的世界状态。帧同步、渲染等待都建立在它上面——"等当前帧结束"五个字,四行实现。

2.4 ThreadSynchronizationContext 全貌:单线程异步的物理基础

源码位于 Core/ThreadSynchronizationContext.cs,全文件 44 行。每个 Fiber 配一个,跨线程回调的唯一落地处——整个 Fiber 模型能成立就靠它。

using System;
using System.Collections.Concurrent;
using System.Threading;

namespace ET
{
    public class ThreadSynchronizationContext : SynchronizationContext
    {
        // 线程同步队列,发送接收socket回调都放到该队列,由poll线程统一执行
        private readonly ConcurrentQueue<Action> queue = new();

        private Action a;

        // ─── 帧末被调用:排空本帧所有跨线程回调 ───
        public void Update()
        {
            while (true)
            {
                if (!this.queue.TryDequeue(out a))
                {
                    return;
                }

                try
                {
                    a();
                }
                catch (Exception e)
                {
                    Log.Error(e);
                }
            }
        }

        // ─── BCL约定入口:await续体从这里进来 ───
        public override void Post(SendOrPostCallback callback, object state)
        {
            this.Post(() => callback(state));
        }

        // ─── 任意线程可入队 ───
        public void Post(Action action)
        {
            this.queue.Enqueue(action);
        }
    }
}

逐段推演:

  • 第 10 行,队列是 ConcurrentQueue<Action>:入队方可以是任意线程(网络线程、定时器线程、别的 Fiber),出队方永远只有 Fiber 自己的那一个线程。读写天然分离,这就是全框架无锁的物理基础——业务代码里找不到一把锁,因为队列本身就是锁的替代品;
  • 第 34-37 行,Post(SendOrPostCallback, object) 这个 override 是 BCL 约定的入口——await 的续体就是被 .NET 以这个签名回调进来的,它包一层 lambda 转成 Action 入队。"在 Fiber 线程里 await 网络请求,回调自动回到 Fiber 线程"并非 ET 的实现,而是 .NET SynchronizationContext 机制自带的,ET 只负责在每个 Fiber 心跳前把正确的上下文立起来;
  • 第 14-32 行,Update() 的 while(true) 一次性排空:本帧的所有跨线程回调集中执行,互不穿插别的线程;每个回调单独 try-catch,一个坏回调记日志,后面的照常执行;
  • 第 12 行 private Action a 复用字段接出队结果,避免热循环反复分配。

2.5 Fiber.Instance 的消费端:Entity 如何一秒找到组织

调度器设置了 Fiber.Instance,业务侧如何消费?Core/Entity/EntityHelper.cs 第 25-29 行:

public static Fiber Fiber(this Entity entity)
{
    return entity.IScene.Fiber;
}

注意:不是 Fiber.Instance——每个 Entity 在 Parent setter 里(Entity.cs:210-218)就已把所属 Scene 的引用缓存了下来(自己是 Scene 则继承父的 Fiber 并把自己登记为 IScene,否则直接抄父的 IScene)。于是 entity.Fiber() 是 O(1) 的字段读取,O(1) 找到所属 Fiber,进而拿到 fiber.Log、fiber.Mailboxes、fiber.ThreadSynchronizationContext.Post(...) 等一切 Fiber 级设施。

Fiber.Instance 真正的用武之地是框架基础设施:调度器、FiberHelper.GetActorId(Fiber.cs:9-13)、以及链路三将看到的跨 Fiber 发送入口。

2.6 两种线程调度:专宠与配额

ThreadScheduler,Core/World/Module/Fiber/ThreadScheduler.cs,全文件 68 行:

using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Threading;

namespace ET
{
    // 一个Fiber一个固定的线程
    internal class ThreadScheduler: IScheduler
    {
        private readonly ConcurrentDictionary<int, Thread> dictionary = new();

        private readonly FiberManager fiberManager;

        public ThreadScheduler(FiberManager fiberManager)
        {
            this.fiberManager = fiberManager;
        }

        // ─── 线程主循环:出生到死亡只服务一个Fiber ───
        private void Loop(int fiberId)
        {
            Fiber fiber = fiberManager.Get(fiberId);
            Fiber.Instance = fiber;
            SynchronizationContext.SetSynchronizationContext(fiber.ThreadSynchronizationContext);

            while (true)
            {
                if (this.fiberManager.IsDisposed())
                {
                    return;
                }

                fiber = fiberManager.Get(fiberId);
                if (fiber == null)
                {
                    this.dictionary.Remove(fiberId, out _);
                    return;
                }

                if (fiber.IsDisposed)
                {
                    this.dictionary.Remove(fiberId, out _);
                    return;
                }

                fiber.Update();
                fiber.LateUpdate();

                Thread.Sleep(1);
            }
        }

        // ─── 收尸:等所有线程跑完当前轮 ───
        public void Dispose()
        {
            foreach (var kv in this.dictionary.ToArray())
            {
                kv.Value.Join();
            }
        }

        // ─── 入伍即开线程 ───
        public void Add(int fiberId)
        {
            Thread thread = new(() => this.Loop(fiberId));
            this.dictionary.TryAdd(fiberId, thread);
            thread.Start();
        }
    }
}

对比主线程调度,三个差异一目了然:

  • 身份只设一次(第 23-24 行):Fiber.Instance 与 SynchronizationContext 在进循环前设置,终身不换——这个线程从出生到死亡只服务这一个 Fiber,连"用完即清"都省了;
  • 三种退出条件每轮都查(第 28-45 行):进程销毁 → 直接 return;Fiber 从字典消失(被 Remove)→ 清掉线程字典再 return;Fiber 自己 IsDisposed → 同上。消亡在线程侧是被观察到的,而不是被通知到的;
  • 第 49 行 Thread.Sleep(1):空转让出时间片。没有消息的 Fiber 也要占着线程睡——所以这种调度只留给"重" Fiber,用一个线程换确定性的微秒级响应。

ThreadPoolScheduler,Core/World/Module/Fiber/ThreadPoolScheduler.cs,全文件 90 行:

using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Threading;

namespace ET
{
    internal class ThreadPoolScheduler: IScheduler
    {
        private readonly List<Thread> threads;

        private readonly ConcurrentQueue<int> idQueue = new();

        private readonly FiberManager fiberManager;

        // ─── 构造:拉起CPU核数个线程 ───
        public ThreadPoolScheduler(FiberManager fiberManager)
        {
            this.fiberManager = fiberManager;
            int threadCount = Environment.ProcessorCount;
            this.threads = new List<Thread>(threadCount);
            for (int i = 0; i < threadCount; ++i)
            {
                Thread thread = new(this.Loop);
                this.threads.Add(thread);
                thread.Start();
            }
        }

        // ─── 工作线程主循环:动态配额轮转 ───
        private void Loop()
        {
            int count = 0;
            while (true)
            {
                if (count <= 0)
                {
                    Thread.Sleep(1);

                    // count最小为1
                    count = this.fiberManager.Count() / this.threads.Count + 1;
                }

                --count;

                if (this.fiberManager.IsDisposed())
                {
                    return;
                }

                if (!this.idQueue.TryDequeue(out int id))
                {
                    Thread.Sleep(1);
                    continue;
                }

                Fiber fiber = this.fiberManager.Get(id);
                if (fiber == null)
                {
                    continue;
                }

                if (fiber.IsDisposed)
                {
                    continue;
                }

                Fiber.Instance = fiber;
                SynchronizationContext.SetSynchronizationContext(fiber.ThreadSynchronizationContext);
                fiber.Update();
                fiber.LateUpdate();
                SynchronizationContext.SetSynchronizationContext(null);
                Fiber.Instance = null;

                this.idQueue.Enqueue(id);
            }
        }

        // ─── 收尸:Join所有工作线程 ───
        public void Dispose()
        {
            foreach (Thread thread in this.threads)
            {
                thread.Join();
            }
        }

        public void Add(int fiberId)
        {
            this.idQueue.Enqueue(fiberId);
        }
    }
}

动态配额是这段的精髓(第 39 行):count = Fiber总数 / 线程数 + 1。代入数字演算:

场景算式每线程每轮配额效果
100 个 Fiber,8 个线程100 / 8 + 1138 线程 × 13 = 104 ≥ 100,全覆盖,多出的 4 个下轮补位,长期均衡
8 个 Fiber,8 个线程8 / 8 + 12每线程跑 2 轮覆盖 16 次调度,Fiber 被多驱动一次,无害
1 个 Fiber,8 个线程1 / 8 + 11若没有 +1,配额为 0,该线程永远 Sleep(1) 空转——Fiber 饿死

+1 是保底,让配额永不为零;整除让配额随 Fiber 规模自动伸缩。配额每轮重新计算:Fiber 增删后自动再均衡,无中心调度、无负载上报。Count() 就是 FiberManager.cs 第 130-133 行那个字典计数。

与主线程调度同构的部分不再重复:同样的双设置(第 66-67 行)、同样的"死亡 Fiber 出队不回队尾"自然淘汰(第 57-64 行)。两个小区别:上下文被显式置 null 而非还原成调度器上下文(第 69 行,工作线程没有"无主默认"的概念,null 就是干净状态);队列空时 Sleep(1) 防忙等(第 51-54 行)。

三种调度器一张表收束:

调度器形态适用场景核心机制
MainThreadN Fiber 共享主线程Unity 客户端每帧快照轮转(addIds 缓冲,LateUpdate 转正)
Thread1 Fiber 独占 1 线程服务端重 Fiber死循环 + Sleep(1),身份终身不换
ThreadPoolN Fiber 共享 M = CPU 核数线程服务端大量轻 Fiber动态配额轮转

动手验证②:在 MainThreadScheduler.Update 的双设置处打断点,条件断点 id == 你的目标FiberId,Watch 里观察 Fiber.Instance.Id 与 SynchronizationContext.Current 的变化——每帧轮转时两个值同步切换、帧末归位,"借线程"的过程一目了然。再做一个反实验:把 SetSynchronizationContext(fiber.ThreadSynchronizationContext) 注释掉,随便找个 await ETTask.CompletedTask 之后的代码打日志,会看到它跑在了 ThreadPool 线程上(线程 Id 突变)——2.2 节反例推演变为现实。


链路三:传信——MessageQueue 与跨 Fiber 消息

这是四条链路中最长的一条。先立一个层次认知,它是这条链路的"魂":MessageQueue(进程级)管"发到哪个 Fiber",Mailboxes(Fiber 级)管"发给哪个 Actor"。前者是跨线程设施,必须并发容器;后者只在 Fiber 内部使用,普通 Dictionary 即可。两级寻址,各安其位。

在主角登场前,先补齐这条链路的几个数据结构——它们是消息在系统中的"肉身",全文反复用到,先认识再上路。

3.0 数据结构四件套

① 门牌:Address 与 ActorId(Core/World/ActorId.cs,全文件 141 行,此处给出核心成员):

// 进程内地址:进程号 + FiberId
[MemoryPackable]
[StructLayout(LayoutKind.Sequential, Pack = 1)]
public partial struct Address
{
    public int Process;
    public int Fiber;
    // ... Equals / == / ToString ...
    public override string ToString() => $"{this.Process}:{this.Fiber}";
}

// 全局 Actor 地址:Address + Entity 的实例 Id
[MemoryPackable]
[StructLayout(LayoutKind.Sequential, Pack = 1)]
public partial struct ActorId
{
    public Address Address;
    public long InstanceId;
    // Process / Fiber 是从 Address 透出的便捷属性
    public override string ToString() => $"{this.Process}:{this.Fiber}:{this.InstanceId}";
}

两个值类型的结构体(StructLayout(Pack=1) 紧凑布局,方便后续网络序列化),ToString 输出的 进程号:FiberId:InstanceId 三段式字符串,就是日志里排查消息流向时最常见的那串数字。

② 信件:MessageInfo(MessageQueue.cs:6-10):ActorId(发件人 + 目标)+ MessageObject(消息体),投递与取件都以它为单元。

③ 包裹:MailBoxInvoker(MailBoxComponent.cs:30-35):FromAddress + MessageObject + MailBoxComponent,邮箱分发给处理器时的封装。

④ 登记单:MessageSenderStruct(Core/Fiber/Module/Actor/MessageSenderStruct.cs):一次 RPC 等待的全部上下文——目标 ActorId、RequestType、NeedException,以及最重要的、内部那个未完成的 ETTask<IResponse>(Call 的 await 挂的就是它)。

最后,ProcessInnerSender 实体类全貌(Core/Fiber/Module/Actor/ProcessInnerSender.cs,全文 16 行)——它的字段就是这条链路的"兵器架":

[ComponentOf(typeof(Scene))]
public class ProcessInnerSender: Entity, IAwake, IDestroy, IUpdate
{
    public const long TIMEOUT_TIME = 40 * 1000;      // 超时阈值:40 秒

    public int RpcId;                                 // 会话编号发生器

    public readonly Dictionary<int, MessageSenderStruct> requestCallback = new();   // 等待中的 RPC 登记

    public readonly List<MessageInfo> list = new();   // 每帧取信的复用缓冲
}

注意三个细节:IUpdate 接口声明(它就是 2.3 节"每帧被驱动"的钩子);超时阈值是 40 秒(40 * 1000 毫秒——对比正文将看到的 200ms 慢调用告警,40 秒是"宁可错杀"的最后底线);这个字典是普通 Dictionary——为什么不用并发容器?先记住这个疑问,3.6 节揭晓。

3.1 ProcessInnerSenderSystem 全貌:Fiber 的"唯一合法嘴"

源码位于 Core/Fiber/Module/Actor/ProcessInnerSenderSystem.cs。这个静态类是 ProcessInnerSender 组件的行为全集。

using System;
using System.Collections.Generic;
using System.IO;

namespace ET
{
    [EntitySystemOf(typeof(ProcessInnerSender))]
    [FriendOf(typeof(ProcessInnerSender))]
    public static partial class ProcessInnerSenderSystem
    {
        // ─── 销户:注销本Fiber的收件格口 ───
        [EntitySystem]
        private static void Destroy(this ProcessInnerSender self)
        {
            Fiber fiber = self.Fiber();
            MessageQueue.Instance.RemoveQueue(fiber.Id);
        }

        // ─── 挂上即开户:在 MessageQueue 注册收件队列 ───
        [EntitySystem]
        private static void Awake(this ProcessInnerSender self)
        {
            Fiber fiber = self.Fiber();
            MessageQueue.Instance.AddQueue(fiber.Id);
        }

        // ─── 每帧开箱:限量取信1000条 ───
        [EntitySystem]
        private static void Update(this ProcessInnerSender self)
        {
            self.list.Clear();
            Fiber fiber = self.Fiber();
            MessageQueue.Instance.Fetch(fiber.Id, 1000, self.list);

            foreach (MessageInfo actorMessageInfo in self.list)
            {
                self.HandleMessage(fiber, actorMessageInfo);
            }
        }

        // ─── 分拣:响应走捷径,其余找Mailbox ───
        private static void HandleMessage(this ProcessInnerSender self, Fiber fiber, in MessageInfo messageInfo)
        {
            if (messageInfo.MessageObject is IResponse response)
            {
                self.HandleIActorResponse(response);
                return;
            }

            ActorId actorId = messageInfo.ActorId;
            MessageObject message = messageInfo.MessageObject;

            MailBoxComponent mailBoxComponent = self.Fiber().Mailboxes.Get(actorId.InstanceId);
            if (mailBoxComponent == null)
            {
                Log.Warning($"actor not found mailbox, from: {actorId} current: {fiber.Address} {message}");
                if (message is IRequest request)
                {
                    IResponse resp = MessageHelper.CreateResponse(request.GetType(), request.RpcId, ErrorCore.ERR_NotFoundActor);
                    self.Reply(actorId.Address, resp);
                }
                return;
            }
            mailBoxComponent.Add(actorId.Address, message);
        }

        // ─── 响应捷径:凭RpcId摘登记项 ───
        private static void HandleIActorResponse(this ProcessInnerSender self, IResponse response)
        {
            if (!self.requestCallback.Remove(response.RpcId, out MessageSenderStruct actorMessageSender))
            {
                return;
            }
            Run(actorMessageSender, response);
        }

        // ─── 唤醒三分支:超时异常/业务异常/正常返回 ───
        private static void Run(MessageSenderStruct self, IResponse response)
        {
            if (response.Error == ErrorCore.ERR_MessageTimeout)
            {
                self.SetException(new RpcException(response.Error, $"Rpc error: request, 注意Actor消息超时,请注意查看是否死锁或者没有reply: actorId: {self.ActorId} {self.RequestType.FullName}, response: {response}"));
                return;
            }

            if (self.NeedException && ErrorCore.IsRpcNeedThrowException(response.Error))
            {
                self.SetException(new RpcException(response.Error, $"Rpc error: actorId: {self.ActorId} request: {self.RequestType.FullName}, response: {response}"));
                return;
            }

            self.SetResult(response);
        }

        // ─── 回件:InstanceId为0,寄给对端的"邮局" ───
        public static void Reply(this ProcessInnerSender self, Address fromAddress, IResponse message)
        {
            self.SendInner(new ActorId(fromAddress, 0), (MessageObject)message);
        }

        public static void Send(this ProcessInnerSender self, ActorId actorId, IMessage message)
        {
            self.SendInner(actorId, (MessageObject)message);
        }

        // ─── 进程内发送的唯一通道 ───
        private static bool SendInner(this ProcessInnerSender self, ActorId actorId, MessageObject message)
        {
            Fiber fiber = self.Fiber();

            // 如果发向同一个进程,则扔到消息队列中
            if (actorId.Process != fiber.Process)
            {
                throw new Exception($"actor inner process diff: {actorId.Process} {fiber.Process}");
            }

            return MessageQueue.Instance.Send(fiber.Address, actorId, message);
        }

        private static int GetRpcId(this ProcessInnerSender self)
        {
            return ++self.RpcId;
        }

        // ─── RPC主入口:Call ───
        public static async ETTask<IResponse> Call(
                this ProcessInnerSender self,
                ActorId actorId,
                IRequest request,
                bool needException = true
        )
        {
            int rpcId = self.GetRpcId();
            request.RpcId = rpcId;

            if (actorId == default)
            {
                throw new Exception($"actor id is 0: {request}");
            }

            Fiber fiber = self.Fiber();
            if (fiber.Process != actorId.Process)
            {
                throw new Exception($"actor inner process diff: {fiber.Process} {actorId.Process}");
            }

            Type requestType = request.GetType();

            IResponse response;
            if (!self.SendInner(actorId, (MessageObject)request))  // 纤程不存在
            {
                response = MessageHelper.CreateResponse(requestType, rpcId, ErrorCore.ERR_NotFoundActor);
                return response;
            }

            MessageSenderStruct messageSenderStruct = new(actorId, requestType, needException);
            self.requestCallback.Add(rpcId, messageSenderStruct);

            async ETTask Timeout()
            {
                await fiber.Root.GetComponent<TimerComponent>().WaitAsync(ProcessInnerSender.TIMEOUT_TIME);

                if (!self.requestCallback.Remove(rpcId, out MessageSenderStruct action))
                {
                    return;
                }

                if (needException)
                {
                    action.SetException(new Exception($"actor sender timeout: {requestType.FullName}"));
                }
                else
                {
                    IResponse response = MessageHelper.CreateResponse(requestType, rpcId, ErrorCore.ERR_Timeout);
                    action.SetResult(response);
                }
            }

            Timeout().Coroutine();

            long beginTime = TimeInfo.Instance.ServerFrameTime();

            response = await messageSenderStruct.Wait();

            long endTime = TimeInfo.Instance.ServerFrameTime();

            long costTime = endTime - beginTime;
            if (costTime > 200)
            {
                Log.Warning($"actor rpc time > 200: {costTime} {requestType.FullName}");
            }

            return response;
        }
    }
}

通读全貌后,这个类的结构非常清晰:Awake/Destroy(12-23 行)管收件格口的开户与销户;Update/HandleMessage(26-61 行)管每帧开箱与两刀分拣;HandleIActorResponse/Run(63-87 行)管响应的唤醒;Reply/Send/SendInner(89-110 行)管出口;Call(117-185 行)是 RPC 主入口。逐段解剖:

3.2 Call 逐段解剖:发送

场景设定:Realm Fiber 里的玩家请求要同步数据,调了 Call(locationActorId, request)。沿第 117-185 行逐段走:

第 124-125 行,分配会话编号:

int rpcId = self.GetRpcId();
request.RpcId = rpcId;

每个 Fiber 一份自增 RpcId(第 112-115 行,单线程自增,无需原子)。RpcId 是本次 RPC 的会话编号,盖章在请求消息上,响应回来时凭它认领。

第 127-136 行,两道防线:

if (actorId == default)
{
    throw new Exception($"actor id is 0: {request}");
}

Fiber fiber = self.Fiber();
if (fiber.Process != actorId.Process)
{
    throw new Exception($"actor inner process diff: {fiber.Process} {actorId.Process}");
}

actorId == default(0 号门牌是非法的);ProcessInnerSender 只管进程内通信,跨进程走网络组件(NetInner),混用直接抛异常——进程边界由类型系统把守,而不是靠约定俗成。

第 140-145 行,快速失败:

Type requestType = request.GetType();

IResponse response;
if (!self.SendInner(actorId, (MessageObject)request))  // 纤程不存在
{
    response = MessageHelper.CreateResponse(requestType, rpcId, ErrorCore.ERR_NotFoundActor);
    return response;
}

SendInner(第 99-110 行)返回 false 表示目标 Fiber 不存在(未创建或已销毁),不等超时,当场构造 ERR_NotFoundActor 错误响应返回。

第 147-148 行,占座:

MessageSenderStruct messageSenderStruct = new(actorId, requestType, needException);
self.requestCallback.Add(rpcId, messageSenderStruct);

登记等待:key 是 RpcId,value 是封装了未完成 ETTask<IResponse> 的 MessageSenderStruct(3.0 节④)。此刻请求已发出,先把"等人回话"的位子占好,响应到达时凭 RpcId 来这认领。

第 150-170 行,超时守护者:

async ETTask Timeout()
{
    await fiber.Root.GetComponent<TimerComponent>().WaitAsync(ProcessInnerSender.TIMEOUT_TIME);

    if (!self.requestCallback.Remove(rpcId, out MessageSenderStruct action))
    {
        return;
    }
    // ... 摘得掉:抛超时异常或返回 ERR_Timeout;摘不掉:静默退出
}

Timeout().Coroutine();

独立的一条协程:定时器到点后去 requestCallback 摘 RpcId——摘得掉说明响应始终没来,按 needException 决定抛异常还是回超时响应;摘不掉(Remove 返回 false)说明响应已先一步被 3.6 节摘除,守护者静默退出。用"摘不摘得掉"这一下判断裁决响应与超时的竞速。它为什么可以放心用普通 Dictionary.Remove?先带着疑问往下看,3.6 节统一揭晓。

第 172-184 行,挂起与慢调用告警:

long beginTime = TimeInfo.Instance.ServerFrameTime();

response = await messageSenderStruct.Wait();

long endTime = TimeInfo.Instance.ServerFrameTime();

long costTime = endTime - beginTime;
if (costTime > 200)
{
    Log.Warning($"actor rpc time > 200: {costTime} {requestType.FullName}");
}

return response;

挂起、被唤醒(怎么唤醒看 3.6 节)。超过 200ms 打警告——注意与 TIMEOUT_TIME = 40 秒 的关系:200ms 是"体验受损但未必出错"的经验阈值(Fiber 间 RPC 本该是微秒级),40 秒是"宁可错杀"的死线。看到 200ms 告警就该排查对端 Fiber 是否死锁或消息拥塞,这是线上诊断的第一线索;40 秒超时则是最后的兜底。

3.3 MessageQueue 全貌:进程内消息的分拣

源码位于 Core/World/Module/Actor/MessageQueue.cs,全文件 68 行,进程级单例。

using System.Collections.Concurrent;
using System.Collections.Generic;

namespace ET
{
    // ─── 一封信:目标ActorId + 消息体 ───
    public struct MessageInfo
    {
        public ActorId ActorId;
        public MessageObject MessageObject;
    }

    public class MessageQueue: Singleton<MessageQueue>, ISingletonAwake
    {
        private readonly ConcurrentDictionary<int, ConcurrentQueue<MessageInfo>> messages = new();

        public void Awake()
        {
        }

        // ─── 寄信(便捷入口) ───
        public bool Send(ActorId actorId, MessageObject messageObject)
        {
            return this.Send(actorId.Address, actorId, messageObject);
        }

        // ─── 回件:丢了不心疼 ───
        public void Reply(ActorId actorId, MessageObject messageObject)
        {
            this.Send(actorId.Address, actorId, messageObject);
        }

        // ─── 寄信主逻辑:按FiberId寻址入队 ───
        public bool Send(Address fromAddress, ActorId actorId, MessageObject messageObject)
        {
            if (!this.messages.TryGetValue(actorId.Address.Fiber, out var queue))
            {
                return false;
            }
            queue.Enqueue(new MessageInfo() {ActorId = new ActorId(fromAddress, actorId.InstanceId), MessageObject = messageObject});
            return true;
        }

        // ─── 取信:收件Fiber自己调用,限量count条 ───
        public void Fetch(int fiberId, int count, List<MessageInfo> list)
        {
            if (!this.messages.TryGetValue(fiberId, out var queue))
            {
                return;
            }

            for (int i = 0; i < count; ++i)
            {
                if (!queue.TryDequeue(out MessageInfo message))
                {
                    break;
                }
                list.Add(message);
            }
        }

        // ─── 开户 / 销户 ───
        public void AddQueue(int fiberId)
        {
            var queue = new ConcurrentQueue<MessageInfo>();
            this.messages[fiberId] = queue;
        }

        public void RemoveQueue(int fiberId)
        {
            this.messages.TryRemove(fiberId, out _);
        }
    }
}

第 14 行那个嵌套并发容器是全文被多线程读写最频繁的基础设施:外层字典 key 是 FiberId,value 是该 Fiber 的收件队列;一个进程所有 Fiber 的进程内邮件都收在这一个字典里,所以两层都是并发容器。

逐段推演:

  • 第 30-38 行 Send:TryGetValue 失败 → 目标 Fiber 不存在 → 返回 false(就是 Call 里快速失败的来源);入队的 ActorId 被重写为 new ActorId(fromAddress, actorId.InstanceId)(第 36 行)——接收方看到的"发件人"是本 Fiber 的 Address + 目标 Entity 的 InstanceId,回件地址在这里一次性铸好;
  • 第 25-28 行 Reply 不回传 bool:回件丢了就丢了(对端可能已销毁),不值得为它抛异常;
  • 第 40-55 行 Fetch:由收件 Fiber 自己在心跳里调用,最多取 count 条进自己的 list。限量就是流控;
  • 第 57-66 行开户/销户:这就是 3.1 里 ProcessInnerSender.Awake/Destroy 调用的两兄弟。组件一挂上,AddQueue 让本 Fiber 在 MessageQueue 拥有收件格口;组件一销毁,RemoveQueue 即刻销户——这正是 Send 里 TryGetValue 可能失败的机制根源。

3.4 每帧开箱与两刀分拣

消息躺在目标 Fiber 的队列里后,要等目标 Fiber 的下一次心跳——回看 ProcessInnerSenderSystem.cs 第 26-36 行:

[EntitySystem]
private static void Update(this ProcessInnerSender self)
{
    self.list.Clear();
    Fiber fiber = self.Fiber();
    MessageQueue.Instance.Fetch(fiber.Id, 1000, self.list);

    foreach (MessageInfo actorMessageInfo in self.list)
    {
        self.HandleMessage(fiber, actorMessageInfo);
    }
}
  • Fetch(fiber.Id, 1000, ...):每帧最多处理 1000 条。一个 Fiber 被消息风暴淹没时,不会把整帧耗死在收信上——剩下的下一帧再说,同线程的其他 Fiber 饿不死。1000 这个数字的权衡:足以摊薄批量取队列的固定开销,又守住了单帧时长上限;
  • 复用 self.list 缓冲,零分配。

第 38-61 行,分拣第一刀:

private static void HandleMessage(this ProcessInnerSender self, Fiber fiber, in MessageInfo messageInfo)
{
    if (messageInfo.MessageObject is IResponse response)
    {
        self.HandleIActorResponse(response);
        return;
    }

响应(IResponse)不进 Mailbox,直接走 RPC 唤醒的捷径。in MessageInfo 修饰符按只读引用传递,避免结构体拷贝。

第二刀:

    ActorId actorId = messageInfo.ActorId;
    MessageObject message = messageInfo.MessageObject;

    MailBoxComponent mailBoxComponent = self.Fiber().Mailboxes.Get(actorId.InstanceId);
    if (mailBoxComponent == null)
    {
        Log.Warning($"actor not found mailbox, from: {actorId} current: {fiber.Address} {message}");
        if (message is IRequest request)
        {
            IResponse resp = MessageHelper.CreateResponse(request.GetType(), request.RpcId, ErrorCore.ERR_NotFoundActor);
            self.Reply(actorId.Address, resp);
        }
        return;
    }
    mailBoxComponent.Add(actorId.Address, message);
}

按目标 Entity 投递:用消息里的 InstanceId 去本 Fiber 的 Mailboxes 找邮箱。找不到说明目标 Entity 已销毁——不能静默丢弃:若这是一条请求(IRequest),必须回一个 ERR_NotFoundActor 错误响应,否则发送方会干等到 40 秒超时。请求-响应协议的礼貌:每个请求都配得上一个响应,哪怕是报错。

3.5 邮箱与分发:Mailbox 是地址牌,不是仓库

Mailboxes 是 Fiber 器官之一,源码位于 Core/Fiber/Mailboxes.cs,全文件 25 行:

using System.Collections.Generic;

namespace ET
{
    public class Mailboxes
    {
        private readonly Dictionary<long, MailBoxComponent> mailboxes = new();

        public void Add(MailBoxComponent mailBoxComponent)
        {
            this.mailboxes.Add(mailBoxComponent.Parent.InstanceId, mailBoxComponent);
        }

        public void Remove(long instanceId)
        {
            this.mailboxes.Remove(instanceId);
        }

        public MailBoxComponent Get(long instanceId)
        {
            this.mailboxes.TryGetValue(instanceId, out MailBoxComponent entity);
            return entity;
        }
    }
}

普通 Dictionary 即可——它在 Fiber 内部使用,单线程语义,无需并发容器。这正是两级寻址的佐证:同样的注册表逻辑,放在进程级就必须付出 ConcurrentDictionary 的代价,放在 Fiber 级就退回最简单的容器。隔离得越彻底,能用的数据结构越简单,这是 Fiber 模型贯穿始终的红利。

再看邮箱本体 Core/Fiber/MailBoxComponent.cs,全文件 47 行,三个部分各司其职:

namespace ET
{
    // ─── 邮箱的System:注册、注销、投递 ───
    [EntitySystemOf(typeof(MailBoxComponent))]
    [FriendOf(typeof(MailBoxComponent))]
    public static partial class MailBoxComponentSystem
    {
        [EntitySystem]
        private static void Awake(this MailBoxComponent self, MailBoxType mailBoxType)
        {
            Fiber fiber = self.Fiber();
            self.MailBoxType = mailBoxType;
            self.ParentInstanceId = self.Parent.InstanceId;
            fiber.Mailboxes.Add(self);
        }

        [EntitySystem]
        private static void Destroy(this MailBoxComponent self)
        {
            self.Fiber().Mailboxes.Remove(self.ParentInstanceId);
        }

        // 加到mailbox
        public static void Add(this MailBoxComponent self, Address fromAddress, MessageObject messageObject)
        {
            // 根据mailboxType进行分发处理
            EventSystem.Instance.Invoke((long)self.MailBoxType, new MailBoxInvoker() {MailBoxComponent = self, MessageObject = messageObject, FromAddress = fromAddress});
        }
    }

    // ─── 投递的包裹 ───
    public struct MailBoxInvoker
    {
        public Address FromAddress;
        public MessageObject MessageObject;
        public MailBoxComponent MailBoxComponent;
    }

    /// <summary>
    /// 挂上这个组件表示该Entity是一个Actor,接收的消息将会队列处理
    /// </summary>
    [ComponentOf]
    public class MailBoxComponent: Entity, IAwake<MailBoxType>, IDestroy
    {
        public long ParentInstanceId { get; set; }
        // Mailbox的类型
        public MailBoxType MailBoxType { get; set; }
    }
}
  • 第 8-14 行 Awake:MailBoxComponent 挂到哪个 Entity 上,哪个 Entity 就是 Actor——类上的注释原文:挂上这个组件表示该Entity是一个Actor,接收的消息将会队列处理。挂组件即注册地址,self.Parent.InstanceId 就是这个 Actor 的门牌号;
  • 第 23-27 行 Add 投递入口:邮箱本身不存消息——它是地址牌 + 调度策略。MailBoxType(Ordered 有序 / UnOrder 无序 / Gate 网关)决定消息进哪个处理器执行,消息的真正排队发生在处理器内部(协程锁排队)。那是 Actor 模型篇的主战场,本文收住,只记住这个论断;
  • 第 17-20 行 Destroy 对称:Actor 实体一销毁,地址即刻失效,后续消息落入 3.4 的"找不到邮箱"分支。

3.6 唤醒:响应如何回到 await

响应消息经分拣第一刀进入第 63-70 行:

private static void HandleIActorResponse(this ProcessInnerSender self, IResponse response)
{
    if (!self.requestCallback.Remove(response.RpcId, out MessageSenderStruct actorMessageSender))
    {
        return;
    }
    Run(actorMessageSender, response);
}

Remove 一把摘掉登记项:摘得掉,正常处理;摘不掉——超时守护者已经先动手,响应作废。同一个 RpcId 在"响应"与"超时"之间只会被成功摘一次,没有一次等待会被回应两次。

现在揭晓 3.0 节埋下的疑问:这个字典是普通 Dictionary,"摘单"竞速凭什么安全?关键在一句话——requestCallback 的一切操作都发生在同一个 Fiber 的线程里。响应的入口是 HandleIActorResponse,来自本 Fiber 每帧的 Update(2.3 节已证);超时回调来自 TimerComponent,它挂在本 Fiber 的 Root 下、由本 Fiber 的 Update 驱动到期,续体经 SynchronizationContext 同样回到本 Fiber 的线程。两个竞争者跑在同一条单行道,字典操作天然串行,根本不需要并发容器。普通 Dictionary 不是偷工减料,而是 Fiber 单线程世界的又一次红利——如果这套 RPC 跑在传统多线程里,这里就得换 ConcurrentDictionary 外加一把锁。

第 72-87 行 Run 三分支:

private static void Run(MessageSenderStruct self, IResponse response)
{
    if (response.Error == ErrorCore.ERR_MessageTimeout)
    {
        self.SetException(new RpcException(response.Error,
            $"Rpc error: request, 注意Actor消息超时,请注意查看是否死锁或者没有reply: ..."));
        return;
    }

    if (self.NeedException && ErrorCore.IsRpcNeedThrowException(response.Error))
    {
        self.SetException(new RpcException(response.Error, $"Rpc error: ..."));
        return;
    }

    self.SetResult(response);
}

对端明确报超时(ERR_MessageTimeout,典型死因——对端 Fiber 死锁或处理完忘了 Reply)→ 抛 RpcException,错误信息直接附排查指引;业务错误码且调用方选择抛异常 → 抛 RpcException;其余 → SetResult 正常唤醒 Call 里 await messageSenderStruct.Wait() 的调用方。

最后补一个让整条链路闭环的细节——响应是怎么"寄回"的?看第 89-92 行 Reply:

public static void Reply(this ProcessInnerSender self, Address fromAddress, IResponse message)
{
    self.SendInner(new ActorId(fromAddress, 0), (MessageObject)message);
}

注意 new ActorId(fromAddress, 0):InstanceId 为 0——响应不寄给任何具体 Actor,而是寄给对端 Fiber 的"邮局"(ProcessInnerSender 组件本身)。它抵达对端后,在 HandleMessage 里要么凭 IResponse 第一刀被截走,要么按 InstanceId=0 找不到任何 Mailbox——两条路都到不了业务 Actor,只能回到 RPC 的等待登记。投递目标与分流逻辑严丝合缝,这个 0 是整套 RPC 协议最不起眼也最关键的一位。

唤醒的续体跑在哪?回看 Call:await 挂起点在发起 Fiber 的线程上,BCL 把续体 Post 回了发起 Fiber 的 ThreadSynchronizationContext——下帧心跳时执行。RPC 的调用方与响应处理在同一个 Fiber 内串行,全程无锁、无线程切换的认知负担。

动手验证③:在 MessageQueue.Send 的 Enqueue 处打断点,Watch Thread.CurrentThread.ManagedThreadId——你会看到它运行在发起方 Fiber 所在的线程上(投递不是异步发送,只是入队)。再在 HandleIActorResponse 打断点,对比两个断点的线程 Id——接收方在自己的线程上被唤醒。最后在 Call 的 await 前后各打一条日志,会发现它们之间隔着若干帧:跨 Fiber 的一次 RPC 至少跨越"对端下一帧开箱"加"发起方再下一帧执行续体"。


链路四:消亡——Remove 与 Create 的镜像对称

回到 FiberManager.cs 第 107-121 行:

public async ETTask Remove(int id)
{
    Fiber fiber = this.Get(id);
    TaskCompletionSource<bool> tcs = new();
    // 要扔到fiber线程执行,否则会出现线程竞争
    fiber.ThreadSynchronizationContext.Post(() =>
    {
        if (this.fibers.Remove(id, out Fiber f))
        {
            f.Dispose();
        }
        tcs.SetResult(true);
    });
    await tcs.Task;
}

与创建完全镜像:创建是"Post 初始化进去",销毁是"Post 销毁进去";注释(第 111 行)再次点题——要扔到fiber线程执行,否则会出现线程竞争。此刻目标 Fiber 可能正在本帧心跳里处理消息、遍历 Entity,从别的线程直接摘字典 + Dispose 就是教科书式的竞争现场。让它死在自己线程上:销毁动作排进它的 ThreadSynchronizationContext,自然落在本帧所有业务之后。await tcs.Task 则给调用方一个确定性的"死透了"信号——与 Create 报错文案里 please await Remove then Create 的规约首尾呼应。

Fiber.Dispose(Fiber.cs:112-121)本体反而简单:幂等保护 + 置标志 + 从根 Scene 级联销毁整棵 Entity 树(树的递归销毁属于 Entity 篇,此处只强调顺序:IsDisposed = true 先行,后到的消息撞上各组件的销毁状态时能感知)。

调度侧的善后是"被动的",回看链路二已讲过的代码,此刻拼上了:

  • MainThreadScheduler.Update(MainThreadScheduler.cs:41-48):死亡 Fiber 出队后不再回队尾,轮转队列自然淘汰;
  • ThreadScheduler.Loop(ThreadScheduler.cs:33-45)的三种退出检查 / ThreadPoolScheduler.Loop(ThreadPoolScheduler.cs:61-64)的两种:线程观察到 Fiber 死亡后自行清字典、自行结束;
  • ProcessInnerSender.Destroy(ProcessInnerSenderSystem.cs:12-16):RemoveQueue 注销收件格口,MessageQueue 同步销户。

没有任何一个调度器需要被"通知"——死亡信息通过共享字典 + 每轮轮询传播,简单粗暴,但在"Fiber 死亡是低频事件"的前提下足够优雅。

动手验证④:Remove 后立刻 Watch MainThreadScheduler.idQueue.Count——它不会立刻减一,要等该 Fiber 下一轮出队时被自然丢弃;再打一条 Fiber.Instance.IsDisposed 的日志观察置位时机。若想看到"销毁动作排在业务之后",在目标 Fiber 的某个 Update 里写一条日志,再在 Remove 的回调里写一条,日志顺序会告诉你:Post 进 ThreadSynchronizationContext 的动作永远排在当帧所有业务之后。

最后进程级收尾,FiberManager.cs 第 49-62 行的 Destroy(ISingletonReverseDispose 标记保证它先于依赖者销毁,进程关闭时先断粮再拆灶):

protected override void Destroy()
{
    foreach (IScheduler scheduler in this.schedulers)
    {
        scheduler.Dispose();
    }

    foreach (var kv in this.fibers)
    {
        kv.Value.Dispose();
    }

    this.fibers = null;
}

先停调度器(线程 Join,等它们跑完当前轮退出),再销毁残留的 Fiber,最后字典置空。顺序即依赖关系:调度器跑着的时候 Fiber 字典必须有效。


总结:ET8 Fiber 机制的架构、实现与价值

总结回顾以上,ET8 的 Fiber 机制是以"串行化消歧、身份双设置、编译期隔离"为三根支柱,通过 FiberManager 统一管理 Fiber 的全生命周期,借 MainThreadScheduler / ThreadScheduler / ThreadPoolScheduler 三种调度策略把 N 个纤程映射到 M 个线程,依托 ThreadSynchronizationContext 将所有跨线程来源统一排队、按序消费,再配合 MessageQueue 与 MailBoxComponent 的两级寻址构建进程内无锁邮路,最终以"Post 到自己线程再执行"的对称手法贯通创建与销毁——用队列替代了锁,用时间片替代了线程,用 internal 替代了约定,把一个进程切成成百上千个彼此隔离、单线程语义的逻辑单元,为上层一切皆 Entity 与 Actor 模型提供了坚实的运行时地基。

Fiber 读透了,下一篇《ETTask:从零造一个可 await 的协程》,继续沿"挂起 → 状态机 → 续体回 ThreadSynchronizationContext"的链路,解剖 await 背后的一切。