BITKit/Packages/Core/Ticker/ThreadHelper.cs

112 lines
3.3 KiB
C#

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<ThreadHelper>(helper);
DI.Register<IThreadTicker>(helper);
}
static ThreadHelper singleton;
public static void LogCurrentThread()
{
var currentTheadID = Thread.CurrentThread.ManagedThreadId.ToString();
BIT4Log.Log<BITApp>($"初始化子线程:{currentTheadID}\n[{DateTime.Now}]");
}
private readonly List<Action<float>> Updates = new();
private readonly List<Action<float>> FixedUpdates = new();
private readonly CancellationToken CancellationToken=new();
private readonly List<Timer> timers = new();
public void AddUpdate(Action<float> action)
{
Updates.Add(action);
}
public void AddFixedUpdate(Action<float> action)
{
FixedUpdates.Add(action);
}
public void RemoveUpdate(Action<float> action)
{
Updates.Remove(action);
}
public void RemoveFixedUpdate(Action<float> 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<ThreadHelper>();
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<Action<float>> 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;
}
}
}