123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128 |
- using System;
- using System.Collections.Concurrent;
- using TBL.CSharp.Game.Server.Message;
- using TBL.CSharp.Game.Server.Process;
- namespace TBL.CSharp.Game.Server;
- /// <summary>
- /// 服务容器
- /// </summary>
- public class ServiceContainer
- {
- /// <summary>
- /// 下一个候选服务句柄
- /// </summary>
- private int _nextServiceHandle;
-
- /// <summary>
- /// 活跃中的服务队列
- /// </summary>
- public readonly ConcurrentQueue<SignalQueue> ActiveSignalQueues;
- /// <summary>
- /// 服务句柄映射
- /// </summary>
- public readonly ConcurrentDictionary<int, Service> ServicesHandleMap;
- /// <summary>
- /// 工作线程封装组
- /// </summary>
- public readonly ConcurrentBag<Worker> Workers;
- public ServiceContainer(
- Func<ServiceContainer, Worker> workerProvider,
- int workerCount
- )
- {
- workerCount = Math.Max(workerCount, 1);
- _nextServiceHandle = 0;
- ActiveSignalQueues = new ConcurrentQueue<SignalQueue>();
- ServicesHandleMap = new ConcurrentDictionary<int, Service>();
- Workers = new ConcurrentBag<Worker>();
- for (var i = 0; i < workerCount; i++)
- {
- var worker = workerProvider(this);
- Workers.Add(worker);
- worker.WorkingThread.Start();
- }
- }
- /// <summary>
- /// 添加服务
- /// </summary>
- public void AddService(Service service)
- {
- if (service.Container != null)
- {
- throw new Exception($"service {service} already added");
- }
- for (;;)
- {
- if (ServicesHandleMap.TryAdd(_nextServiceHandle, service))
- {
- service.Handle = _nextServiceHandle;
- service.Container = this;
- break;
- }
- if (_nextServiceHandle == int.MaxValue)
- _nextServiceHandle = 0;
- else
- _nextServiceHandle += 1;
- }
- }
- /// <summary>
- /// 解析出服务句柄
- /// </summary>
- public int ResolveServiceHandle(string name)
- {
- lock (ServicesHandleMap)
- {
- foreach (var pair in ServicesHandleMap)
- {
- if (name == pair.Value.GetType().FullName)
- return pair.Key;
- }
- }
- return -1;
- }
- /// <summary>
- /// 向指定服务传递信号
- /// </summary>
- public void Send(Signal signal)
- {
- if (ServicesHandleMap.TryGetValue(signal.TargetAddress.ServiceHandle, out var targetService))
- {
- var queue = targetService.SignalQueue;
- queue.Enqueue(signal);
- // 对队列加锁
- lock (queue)
- {
- // 非活跃的情况下,使其进入活跃序列
- if (!queue.ActiveLock)
- {
- queue.ActiveLock = true;
- ActiveSignalQueues.Enqueue(queue);
- }
- }
- }
- }
- /// <summary>
- /// 清空
- /// </summary>
- public void Clear(bool forceStop = false)
- {
- // 工作线程关闭
- while (Workers.TryTake(out var worker))
- {
- if (forceStop)
- worker.WorkingThread.Abort();
- else
- worker.RequestStop();
- }
- }
- }
|