diff --git a/GFramework.Core/coroutine/CoroutineScheduler.cs b/GFramework.Core/coroutine/CoroutineScheduler.cs index 89b3753..2ccf9a3 100644 --- a/GFramework.Core/coroutine/CoroutineScheduler.cs +++ b/GFramework.Core/coroutine/CoroutineScheduler.cs @@ -56,7 +56,8 @@ public sealed class CoroutineScheduler( var slot = new CoroutineSlot { Enumerator = coroutine, - State = CoroutineState.Running + State = CoroutineState.Running, + Handle = handle }; _slots[slotIndex] = slot; @@ -88,7 +89,7 @@ public sealed class CoroutineScheduler( for (var i = 0; i < _nextSlot; i++) { var slot = _slots[i]; - if (slot == null || slot.State != CoroutineState.Running) + if (slot is not { State: CoroutineState.Running }) continue; try @@ -207,7 +208,7 @@ public sealed class CoroutineScheduler( if (!_waiting.TryGetValue(target, out var set)) { - set = new HashSet(); + set = []; _waiting[target] = set; } @@ -223,15 +224,8 @@ public sealed class CoroutineScheduler( { if (!_tagged.TryGetValue(tag, out var handles)) return 0; - var copy = handles.ToArray(); - var count = 0; - - foreach (var h in copy) - if (Kill(h)) - count++; - - return count; + return copy.Count(Kill); } /// @@ -294,43 +288,28 @@ public sealed class CoroutineScheduler( if (slot == null) return; - _slots[slotIndex] = null; - _activeCount--; - - CoroutineHandle handle = default; - foreach (var kv in _metadata) - { - if (kv.Value.SlotIndex == slotIndex) - { - handle = kv.Key; - break; - } - } - + var handle = slot.Handle; if (!handle.IsValid) return; + _slots[slotIndex] = null; + _activeCount--; + RemoveTag(handle); _metadata.Remove(handle); // 唤醒等待者 - if (_waiting.TryGetValue(handle, out var waiters)) + if (!_waiting.TryGetValue(handle, out var waiters)) return; + foreach (var waiter in waiters) { - foreach (var waiter in waiters) - { - if (_metadata.TryGetValue(waiter, out var meta)) - { - var s = _slots[meta.SlotIndex]; - if (s != null) - { - s.State = CoroutineState.Running; - meta.State = CoroutineState.Running; - } - } - } - - _waiting.Remove(handle); + if (!_metadata.TryGetValue(waiter, out var meta)) continue; + var s = _slots[meta.SlotIndex]; + if (s == null) continue; + s.State = CoroutineState.Running; + meta.State = CoroutineState.Running; } + + _waiting.Remove(handle); } /// diff --git a/GFramework.Core/coroutine/CoroutineSlot.cs b/GFramework.Core/coroutine/CoroutineSlot.cs index 9176161..4c796e8 100644 --- a/GFramework.Core/coroutine/CoroutineSlot.cs +++ b/GFramework.Core/coroutine/CoroutineSlot.cs @@ -21,4 +21,9 @@ internal sealed class CoroutineSlot /// 当前等待的指令,用于控制协程的暂停和恢复 /// public IYieldInstruction? Waiting; -} \ No newline at end of file + + /// + /// 协程句柄,用于标识和管理协程实例 + /// + public CoroutineHandle Handle; +}