123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110 |
- using System;
- using System.Threading;
- using TBL.CSharp.Game.Server.Message;
- namespace TBL.CSharp.Game.Server.Process;
- /// <summary>
- /// 工作线程的封装
- /// </summary>
- public class Worker
- {
- /// <summary>
- /// 工作线程
- /// </summary>
- public readonly Thread WorkingThread;
-
- /// <summary>
- /// 工作线程应当继续运行
- /// </summary>
- private bool _threadShouldRunning;
- public unsafe Worker(ServiceContainer container)
- {
- _threadShouldRunning = true;
- WorkingThread = new Thread(() =>
- {
- SignalQueue queue;
- Signal signal;
- while (_threadShouldRunning)
- {
- OnLoopStart();
- // 从活跃服务队列中获取一个队列
- if (!container.ActiveSignalQueues.TryDequeue(out queue))
- {
- // 空队列的情况下节省 cpu 时间
- OnSignalQueueEmpty();
- continue;
- }
- // 对活跃队列加锁
- lock (queue)
- {
- // 队列已从活跃序列中移走
- queue.ActiveLock = false;
- // 队列中有消息
- if (queue.TryDequeue(out signal))
- {
- try
- {
- // 处理消息,此过程能保证线程安全
- queue.Owner.OnSignal(signal, container);
- }
- catch (Exception e)
- {
- // 异常处理
- OnServiceCallbackException(e);
- }
- // 如果信号携带数据,此时可以回收内存
- if (!signal.Data.IsNullPtr)
- signal.Data.Free();
- // 归还队列
- queue.ActiveLock = true;
- container.ActiveSignalQueues.Enqueue(queue);
- }
- }
- }
- // 终结流程
- OnTerminated();
- });
- }
- /// <summary>
- /// 停止
- /// </summary>
- public void RequestStop()
- {
- _threadShouldRunning = false;
- }
- /// <summary>
- /// 工作中
- /// </summary>
- public bool IsWorking => WorkingThread.IsAlive && _threadShouldRunning;
-
- /// <summary>
- /// 消息队列为空时触发
- /// <para>通常用于解脱 cpu 控制</para>
- /// </summary>
- public virtual void OnSignalQueueEmpty() => Thread.Yield();
- /// <summary>
- /// 服务回调异常时触发
- /// </summary>
- public virtual void OnServiceCallbackException(Exception e)
- {
- }
-
- /// <summary>
- /// 终结时触发
- /// </summary>
- public virtual void OnTerminated()
- {
- }
- /// <summary>
- /// 主循环一轮开始时触发
- /// </summary>
- public virtual void OnLoopStart()
- {
- }
- }
|