using System; using System.Collections; using System.Collections.Generic; using System.Collections.Concurrent; using System.Threading; using System.Threading.Tasks; using Timer = System.Timers.Timer; using Cysharp.Threading.Tasks; using System.Text; namespace BITKit { public class ThreadHelper : IThreadTicker { internal static void InitAPP() { ThreadHelper helper = new(); singleton = helper; DI.Register(helper); DI.Register(helper); } static ThreadHelper singleton; public static void LogCurrentThread() { var currentTheadID = Thread.CurrentThread.ManagedThreadId.ToString(); BIT4Log.Log($"初始化子线程:{currentTheadID}\n[{DateTime.Now}]"); } private readonly List> Updates = new(); private readonly List> FixedUpdates = new(); private readonly CancellationToken CancellationToken=new(); private readonly List timers = new(); public void AddUpdate(Action action) { Updates.Add(action); } public void AddFixedUpdate(Action action) { FixedUpdates.Add(action); } public void RemoveUpdate(Action action) { Updates.Remove(action); } public void RemoveFixedUpdate(Action action) { FixedUpdates.Remove(action); } public void Add(Action action) { try { new Thread(action.Invoke).Start(); } catch (System.Exception e) { BIT4Log.LogException(e); } } [ExcuteOnAwake] public static void Start() { var ticker = DI.Get(); singleton = ticker; new Thread(singleton.Init).Start(); } [ExcuteOnStop] public static void Stop() { foreach (var timer in singleton.timers) { timer.Stop(); timer.Dispose(); } singleton.Updates.Clear(); singleton.FixedUpdates.Clear(); } void Init() { CreateTimer(Updates, 1 / 64f); CreateTimer(FixedUpdates, 1 / 32f); } Timer CreateTimer(List> actions, float deltaTime) { Timer timer = new(); timer.Interval = TimeSpan.FromSeconds(deltaTime).Milliseconds; timer.Elapsed += (x, y) => { try { CancellationToken.ThrowIfCancellationRequested(); foreach (var action in actions.ToArray()) { action.Invoke(deltaTime); } } catch (System.OperationCanceledException) { return; } catch (System.Exception e) { BIT4Log.LogException(e); } }; timer.AutoReset = true; timer.Enabled = true; timer.Start(); timers.Add(timer); return timer; } } }