refactor(coroutine): 优化 WaitForAllCoroutines 实现逻辑

- 将字段初始化改为构造函数中赋值
- 添加 _isDone 字段缓存完成状态
- 在构造函数中预处理空列表情况
- 优化 Update 方法减少重复计算
- 简化 IsDone 属性实现
- 提升协程等待性能
This commit is contained in:
GeWuYou 2026-02-01 15:16:15 +08:00
parent 120fd14cd8
commit b4360b01ca

View File

@ -5,23 +5,30 @@ namespace GFramework.Core.coroutine.instructions;
/// <summary>
/// 等待所有协程完成的等待指令
/// </summary>
public sealed class WaitForAllCoroutines(
CoroutineScheduler scheduler,
IReadOnlyList<CoroutineHandle> handles)
: IYieldInstruction
public sealed class WaitForAllCoroutines : IYieldInstruction
{
private readonly IReadOnlyList<CoroutineHandle> _handles =
handles ?? throw new ArgumentNullException(nameof(handles));
private readonly IReadOnlyList<CoroutineHandle> _handles;
private readonly CoroutineScheduler _scheduler;
private bool _isDone;
private readonly CoroutineScheduler _scheduler = scheduler ?? throw new ArgumentNullException(nameof(scheduler));
public WaitForAllCoroutines(
CoroutineScheduler scheduler,
IReadOnlyList<CoroutineHandle> handles)
{
_scheduler = scheduler ?? throw new ArgumentNullException(nameof(scheduler));
_handles = handles ?? throw new ArgumentNullException(nameof(handles));
// 空列表直接完成
_isDone = _handles.Count == 0;
}
public void Update(double deltaTime)
{
// 不需要做任何事
if (_isDone) return;
// 检查所有协程是否都已完成
_isDone = _handles.All(handle => !_scheduler.IsCoroutineAlive(handle));
}
public bool IsDone
{
get { return _handles.All(handle => !_scheduler.IsCoroutineAlive(handle)); }
}
public bool IsDone => _isDone;
}