From 6cc2bdfeb5740882275e918eafbe2308ba8c4865 Mon Sep 17 00:00:00 2001 From: GeWuYou <95328647+GeWuYou@users.noreply.github.com> Date: Mon, 9 Feb 2026 19:16:22 +0800 Subject: [PATCH] =?UTF-8?q?refactor(coroutine):=20=E4=BC=98=E5=8C=96?= =?UTF-8?q?=E5=BC=82=E6=AD=A5=E6=93=8D=E4=BD=9C=E5=BB=B6=E7=BB=AD=E5=A4=84?= =?UTF-8?q?=E7=90=86=E9=80=BB=E8=BE=91?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 使用while循环替代递归调用避免栈溢出风险 - 改进CAS操作的重试机制提高并发安全性 - 简化空值检查逻辑提升代码可读性 - 优化双重检查锁模式确保线程安全 --- .../coroutine/instructions/AsyncOperation.cs | 41 +++++++++++-------- 1 file changed, 23 insertions(+), 18 deletions(-) diff --git a/GFramework.Core/coroutine/instructions/AsyncOperation.cs b/GFramework.Core/coroutine/instructions/AsyncOperation.cs index 3f67940..c138aef 100644 --- a/GFramework.Core/coroutine/instructions/AsyncOperation.cs +++ b/GFramework.Core/coroutine/instructions/AsyncOperation.cs @@ -28,27 +28,32 @@ public class AsyncOperation : IYieldInstruction, INotifyCompletion /// 要执行的延续操作 public void OnCompleted(Action continuation) { - // 尝试添加延续 - var current = _continuation; - var newContinuation = current == null ? continuation : current + continuation; - - if (Interlocked.CompareExchange(ref _continuation, newContinuation, current) != current) + while (true) { - // 如果CAS失败,说明可能已经完成,直接执行 + // 尝试添加延续 + var current = _continuation; + var newContinuation = current == null ? continuation : current + continuation; + + if (Interlocked.CompareExchange(ref _continuation, newContinuation, current) != current) + { + // 如果CAS失败,说明可能已经完成,直接执行 + if (_completed) + continuation(); + else + // 重试 + continue; + + return; + } + + // 双重检查:如果在设置延续后发现已完成,需要执行延续 if (_completed) - continuation(); - else - // 重试 - OnCompleted(continuation); + { + var cont = Interlocked.Exchange(ref _continuation, null); + cont?.Invoke(); + } - return; - } - - // 双重检查:如果在设置延续后发现已完成,需要执行延续 - if (_completed) - { - var cont = Interlocked.Exchange(ref _continuation, null); - if (cont != null) cont(); + break; } }