wanshenmean
2026-03-27 bf2aa9dd56432a74940ca1bb08fb4d7eaee37045
Code/WCS/WIDESEAWCS_Server/WIDESEAWCS_Tasks/RobotJob/RobotStateManager.cs
@@ -1,6 +1,8 @@
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using WIDESEAWCS_Common;
using WIDESEAWCS_Core.Caches;
using WIDESEAWCS_Core.LogHelper;
using WIDESEAWCS_QuartzJob;
namespace WIDESEAWCS_Tasks
@@ -20,12 +22,19 @@
        private readonly ICacheService _cache;
        /// <summary>
        /// 日志记录器
        /// </summary>
        private readonly ILogger _logger;
        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="cache">缓存服务实例(通常为 HybridCacheService)</param>
        public RobotStateManager(ICacheService cache)
        /// <param name="logger">日志记录器</param>
        public RobotStateManager(ICacheService cache, ILogger logger)
        {
            _cache = cache;
            _logger = logger;
        }
        /// <summary>
@@ -100,6 +109,8 @@
                newState.Version = DateTime.UtcNow.Ticks;
                // 直接添加到缓存
                _cache.AddObject(cacheKey, newState);
                _logger.LogDebug("TryUpdateStateSafely:创建新状态,IP: {IpAddress}", ipAddress);
                QuartzLogger.Debug($"创建新状态,IP: {ipAddress}", ipAddress);
                return true;
            }
@@ -110,12 +121,20 @@
            newState.Version = DateTime.UtcNow.Ticks;
            // 尝试安全更新,如果版本冲突则返回 false
            return _cache.TrySafeUpdate(
            bool success = _cache.TrySafeUpdate(
                cacheKey,
                newState,
                expectedVersion,
                s => s.Version
            );
            if (!success)
            {
                _logger.LogWarning("TryUpdateStateSafely:版本冲突,更新失败,IP: {IpAddress},期望版本: {ExpectedVersion}", ipAddress, expectedVersion);
                QuartzLogger.Warn($"版本冲突,更新失败,IP: {ipAddress}", ipAddress);
            }
            return success;
        }
        /// <summary>