refactor : 重构代码

This commit is contained in:
何冠峰
2026-01-17 16:12:03 +08:00
parent 3e3661ad95
commit da222c6179
9 changed files with 269 additions and 315 deletions
@@ -10,17 +10,22 @@ namespace YooAsset
{
private List<AsyncOperationBase> _childs;
private Action<AsyncOperationBase> _callback;
private uint _priority = 0;
private uint _priority;
/// <summary>
/// 等待异步执行完成
/// </summary>
internal bool IsWaitForAsyncComplete { private set; get; } = false;
internal bool IsWaitForAsyncComplete { get; private set; }
/// <summary>
/// 标记脏(用于调度器检测并重排)
/// </summary>
internal bool IsDirty { get; set; }
/// <summary>
/// 是否已经完成
/// </summary>
internal bool IsFinish { private set; get; } = false;
internal bool IsFinish { get; private set; }
/// <summary>
/// 异步系统是否繁忙
@@ -35,11 +40,6 @@ namespace YooAsset
}
}
/// <summary>
/// 标记脏(用于调度器检测并重排)
/// </summary>
internal bool IsDirty { set; get; } = false;
/// <summary>
/// 任务优先级
/// </summary>
@@ -98,6 +98,7 @@ namespace YooAsset
{
try
{
//注意:任务已完成,立即调用回调
value.Invoke(this);
}
catch (Exception ex)
@@ -295,21 +296,25 @@ namespace YooAsset
// 结束记录
DebugEndRecording();
try
if (_callback != null)
{
//TODO 单个回调异常会阻断后续订阅者
_callback?.Invoke(this);
}
catch (Exception ex)
{
YooLogger.Error($"Exception in completion callback: {ex}");
}
finally
{
_callback = null;
if (_taskCompletionSource != null)
_taskCompletionSource.TrySetResult(null);
var invocationList = _callback.GetInvocationList();
foreach (var handler in invocationList)
{
try
{
((Action<AsyncOperationBase>)handler).Invoke(this);
}
catch (Exception ex)
{
YooLogger.Error($"Exception in completion callback: {ex}");
}
}
}
_callback = null;
if (_taskCompletionSource != null)
_taskCompletionSource.TrySetResult(null);
}
}
@@ -327,7 +332,10 @@ namespace YooAsset
/// <summary>
/// 批量执行一定次数的更新逻辑
/// </summary>
/// <param name="count">次数</param>
/// <param name="count">最大执行次数,默认1000次</param>
/// <remarks>
/// 用于需要快速完成但又不想完全阻塞主线程的场景。
/// </remarks>
protected void RunBatchExecution(int count = 1000)
{
if (IsDone)
@@ -374,7 +382,7 @@ namespace YooAsset
/// </summary>
public void WaitForAsyncComplete()
{
//TODO 防止异步操作被挂起陷入无限死循环!
//注意:防止异步操作被挂起陷入无限死循环!
if (Status == EOperationStatus.None)
{
StartOperation();
@@ -400,15 +408,17 @@ namespace YooAsset
}
#region 调试信息
private const int MaxCycleCheckDepth = 4096; // 循环检测最大深度
/// <summary>
/// 开始的时间
/// </summary>
public string BeginTime { protected set; get; }
public string BeginTime { get; protected set; }
/// <summary>
/// 处理耗时(单位:毫秒)
/// </summary>
public long ProcessTime { protected set; get; }
public long ProcessTime { get; protected set; }
// 加载耗时统计
private Stopwatch _watch = null;
@@ -449,9 +459,13 @@ namespace YooAsset
double s = System.Math.Floor(spawnTime - m * 60 - h * 3600);
return h.ToString("00") + ":" + m.ToString("00") + ":" + s.ToString("00");
}
/// <summary>
/// 检测添加子任务是否会形成循环依赖
/// 使用深度优先搜索(DFS)遍历子任务图
/// </summary>
private bool WouldCreateCycle(AsyncOperationBase child)
{
const int maxVisited = 4096;
var stack = new Stack<AsyncOperationBase>();
var visited = new HashSet<AsyncOperationBase>();
stack.Push(child);
@@ -462,18 +476,22 @@ namespace YooAsset
if (node == null)
continue;
// 防止重复访问
if (visited.Add(node) == false)
continue;
if (visited.Count > maxVisited)
// 防止无限循环(图过大)
if (visited.Count > MaxCycleCheckDepth)
throw new YooInternalException("Child operation graph is too large, cycle check aborted !");
// 检测循环:如果遍历到自己,说明形成循环
if (ReferenceEquals(node, this))
return true;
if (node._childs == null)
continue;
// 将子节点加入栈
for (int i = 0; i < node._childs.Count; i++)
{
stack.Push(node._childs[i]);
@@ -10,12 +10,12 @@ namespace YooAsset
{
private readonly List<AsyncOperationBase> _operations = new List<AsyncOperationBase>(100);
private readonly List<AsyncOperationBase> _newList = new List<AsyncOperationBase>(100);
private uint _priority = 0;
private uint _priority;
/// <summary>
/// 所属包裹名称
/// </summary>
public string PackageName { private set; get; }
public string PackageName { get; private set; }
/// <summary>
/// 调度器优先级(值越大越优先)
@@ -36,12 +36,12 @@ namespace YooAsset
/// <summary>
/// 优先级是否已变更(需要重新排序)
/// </summary>
public bool IsDirty { set; get; } = false;
public bool IsDirty { get; set; }
/// <summary>
/// 创建顺序(用于同优先级稳定排序)
/// </summary>
public int CreateIndex { private set; get; }
public int CreateIndex { get; private set; }
public OperationScheduler(string packageName, int createIndex)
@@ -53,6 +53,9 @@ namespace YooAsset
/// <summary>
/// 开始处理异步操作
/// </summary>
/// <remarks>
/// 操作会先添加到临时队列,在下一次Update时才会开始执行
/// </remarks>
public void StartOperation(AsyncOperationBase operation)
{
_newList.Add(operation);
@@ -15,13 +15,13 @@ namespace YooAsset
}
#endif
// 全局调度器名称
public const string GLOBAL_SCHEDULER_NAME = "YOOASSET_GLOBAL_SCHEDULER";
public const string GlobalSchedulerName = "YOOASSET_GLOBAL_SCHEDULER"; // 全局调度器名称
private const long MinTimeSlice = 10; // 最小时间片(毫秒)
private static readonly Dictionary<string, OperationScheduler> _schedulerDic = new Dictionary<string, OperationScheduler>(100);
private static readonly List<OperationScheduler> _schedulerList = new List<OperationScheduler>(100);
private static bool _isInitialize = false;
private static int _createIndex = 0;
private static bool _isInitialized;
private static int _createIndex;
// 计时器相关
private static Stopwatch _watch;
@@ -33,12 +33,16 @@ namespace YooAsset
/// </summary>
public static long MaxTimeSlice
{
get
{
return _maxTimeSlice;
}
set
{
if (value < 10)
if (value < MinTimeSlice)
{
_maxTimeSlice = 10;
YooLogger.Warning($"MaxTimeSlice minimum value is 10 milliseconds.");
_maxTimeSlice = MinTimeSlice;
YooLogger.Warning($"MaxTimeSlice minimum value is {MinTimeSlice} milliseconds.");
}
else
{
@@ -71,14 +75,17 @@ namespace YooAsset
/// </summary>
public static void Initialize()
{
if (_isInitialize == false)
if (_isInitialized)
{
_isInitialize = true;
_watch = Stopwatch.StartNew();
// 创建全局调度器
CreatePackageScheduler(GLOBAL_SCHEDULER_NAME, uint.MaxValue);
YooLogger.Warning("Operation system is already initialized!");
return;
}
_isInitialized = true;
_watch = Stopwatch.StartNew();
// 创建全局调度器
CreatePackageScheduler(GlobalSchedulerName, uint.MaxValue);
}
/// <summary>
@@ -86,7 +93,7 @@ namespace YooAsset
/// </summary>
public static void Update()
{
if (_isInitialize == false)
if (_isInitialized == false)
return;
// 检测是否需要执行排序
@@ -122,8 +129,7 @@ namespace YooAsset
/// </summary>
public static void DestroyAll()
{
_isInitialize = false;
YooLogger.Log("Operation system destroy all !");
_isInitialized = false;
// 清空所有调度器
foreach (var scheduler in _schedulerList)
@@ -136,7 +142,7 @@ namespace YooAsset
_watch = null;
_frameTime = 0;
MaxTimeSlice = long.MaxValue;
_maxTimeSlice = long.MaxValue;
}
/// <summary>
@@ -144,7 +150,7 @@ namespace YooAsset
/// </summary>
public static OperationScheduler CreatePackageScheduler(string packageName, uint priority)
{
DebugCheckInitialize(packageName);
DebugEnsureInitialized(packageName);
if (_schedulerDic.ContainsKey(packageName))
{
@@ -163,10 +169,10 @@ namespace YooAsset
/// </summary>
public static void DestroyPackageScheduler(string packageName)
{
DebugCheckInitialize(packageName);
DebugEnsureInitialized(packageName);
// 不允许销毁默认调度器
if (packageName == GLOBAL_SCHEDULER_NAME)
if (packageName == GlobalSchedulerName)
{
throw new YooInternalException("Cannot destroy the global package scheduler!");
}
@@ -184,7 +190,7 @@ namespace YooAsset
/// </summary>
public static void ClearPackageOperation(string packageName)
{
DebugCheckInitialize(packageName);
DebugEnsureInitialized(packageName);
var scheduler = GetScheduler(packageName);
scheduler.ClearAll();
@@ -195,7 +201,7 @@ namespace YooAsset
/// </summary>
public static void StartOperation(string packageName, AsyncOperationBase operation)
{
DebugCheckInitialize(packageName);
DebugEnsureInitialized(packageName);
var scheduler = GetScheduler(packageName);
scheduler.StartOperation(operation);
@@ -206,7 +212,7 @@ namespace YooAsset
/// </summary>
public static void SetSchedulerPriority(string packageName, uint priority)
{
DebugCheckInitialize(packageName);
DebugEnsureInitialized(packageName);
var scheduler = GetScheduler(packageName);
scheduler.Priority = priority;
@@ -217,7 +223,7 @@ namespace YooAsset
/// </summary>
public static uint GetSchedulerPriority(string packageName)
{
DebugCheckInitialize(packageName);
DebugEnsureInitialized(packageName);
var scheduler = GetScheduler(packageName);
return scheduler.Priority;
@@ -240,7 +246,7 @@ namespace YooAsset
#region 调试信息
internal static List<DebugOperationInfo> GetDebugOperationInfos(string packageName)
{
DebugCheckInitialize(packageName);
DebugEnsureInitialized(packageName);
var scheduler = GetScheduler(packageName);
return scheduler.GetDebugOperationInfos();
@@ -249,12 +255,12 @@ namespace YooAsset
#region 调试方法
[Conditional("DEBUG")]
private static void DebugCheckInitialize(string packageName)
private static void DebugEnsureInitialized(string packageName)
{
if (string.IsNullOrWhiteSpace(packageName))
throw new YooInternalException("Package name is null or empty.");
if (_isInitialize == false)
if (_isInitialized == false)
throw new YooInternalException($"{nameof(OperationSystem)} not initialized !");
}
#endregion