diff --git a/GFramework.Core.Abstractions/state/IAsyncState.cs b/GFramework.Core.Abstractions/state/IAsyncState.cs index 729b8ae..517642b 100644 --- a/GFramework.Core.Abstractions/state/IAsyncState.cs +++ b/GFramework.Core.Abstractions/state/IAsyncState.cs @@ -16,7 +16,7 @@ namespace GFramework.Core.Abstractions.state; /// /// 异步状态机状态接口,定义了状态的异步行为和转换规则 /// -public interface IAsyncState +public interface IAsyncState : IState { /// /// 当状态被激活进入时异步调用 diff --git a/GFramework.Core/state/AsyncContextAwareStateBase.cs b/GFramework.Core/state/AsyncContextAwareStateBase.cs index 266a610..368641e 100644 --- a/GFramework.Core/state/AsyncContextAwareStateBase.cs +++ b/GFramework.Core/state/AsyncContextAwareStateBase.cs @@ -61,6 +61,39 @@ public class AsyncContextAwareStateBase : IAsyncState, IContextAware, IDisposabl return Task.FromResult(true); } + /// + /// 同步进入状态(不推荐使用) + /// 异步状态应该使用 OnEnterAsync 方法 + /// + /// 异步状态不支持同步操作 + public virtual void OnEnter(IState? from) + { + throw new NotSupportedException( + $"This is an async state ({GetType().Name}). Use OnEnterAsync instead of OnEnter."); + } + + /// + /// 同步退出状态(不推荐使用) + /// 异步状态应该使用 OnExitAsync 方法 + /// + /// 异步状态不支持同步操作 + public virtual void OnExit(IState? to) + { + throw new NotSupportedException( + $"This is an async state ({GetType().Name}). Use OnExitAsync instead of OnExit."); + } + + /// + /// 同步判断是否可以转换(不推荐使用) + /// 异步状态应该使用 CanTransitionToAsync 方法 + /// + /// 异步状态不支持同步操作 + public virtual bool CanTransitionTo(IState target) + { + throw new NotSupportedException( + $"This is an async state ({GetType().Name}). Use CanTransitionToAsync instead of CanTransitionTo."); + } + /// /// 设置架构上下文 /// diff --git a/GFramework.Core/state/StateMachine.cs b/GFramework.Core/state/StateMachine.cs index 70f4495..4ffd820 100644 --- a/GFramework.Core/state/StateMachine.cs +++ b/GFramework.Core/state/StateMachine.cs @@ -138,20 +138,23 @@ public class StateMachine(int maxHistorySize = 10) : IStateMachine public async Task ChangeToAsync() where T : IState { IState target; + IState? currentSnapshot; lock (_lock) { if (!States.TryGetValue(typeof(T), out target!)) throw new InvalidOperationException($"State {typeof(T).Name} not registered."); + + currentSnapshot = Current; // 在锁内获取当前状态的快照 } // 验证转换(在锁外执行异步操作) - if (Current != null) + if (currentSnapshot != null) { - var canTransition = await CanTransitionToAsync(Current, target); + var canTransition = await CanTransitionToAsync(currentSnapshot, target); if (!canTransition) { - await OnTransitionRejectedAsync(Current, target); + await OnTransitionRejectedAsync(currentSnapshot, target); return false; } }