using System;
using System.Threading;
using TBL.CSharp.Game.Server.Message;
namespace TBL.CSharp.Game.Server.Process;
///
/// 工作线程的封装
///
public class Worker
{
///
/// 工作线程
///
public readonly Thread WorkingThread;
///
/// 工作线程应当继续运行
///
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();
});
}
///
/// 停止
///
public void RequestStop()
{
_threadShouldRunning = false;
}
///
/// 工作中
///
public bool IsWorking => WorkingThread.IsAlive && _threadShouldRunning;
///
/// 消息队列为空时触发
/// 通常用于解脱 cpu 控制
///
public virtual void OnSignalQueueEmpty() => Thread.Yield();
///
/// 服务回调异常时触发
///
public virtual void OnServiceCallbackException(Exception e)
{
}
///
/// 终结时触发
///
public virtual void OnTerminated()
{
}
///
/// 主循环一轮开始时触发
///
public virtual void OnLoopStart()
{
}
}