using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Microsoft.Extensions.Logging; namespace CoreAgent.ProtocolClient.Context.UeStateManager { /// /// UeIdentifierManager 字符串ID管理部分 /// public partial class UeIdentifierManager { #region 字符串ID管理方法 /// /// 将字符串转换为ID,如果不存在则创建新的ID /// 性能优化:使用缓存减少重复计算 /// /// 要转换的字符串 /// 对应的ID /// 字符串为空时抛出 public int StringToId(string str) { if (string.IsNullOrEmpty(str)) { _logger?.LogWarning("尝试转换空字符串为ID"); return 0; } lock (_lockObject) { IncrementCacheStat("StringToId"); if (_stringIdCache.TryGetValue(str, out int existingId)) { IncrementCacheStat("CacheHits"); return existingId; } IncrementCacheStat("CacheMisses"); int newId = _stringList.Count + 1; _stringIdCache[str] = newId; _stringList.Add(str); _logger?.LogDebug("创建新的字符串ID映射: '{String}' -> {Id}", str, newId); return newId; } } /// /// 根据ID获取对应的字符串 /// 性能优化:使用缓存减少重复计算 /// /// 字符串ID /// 对应的字符串,如果ID无效则返回空字符串 public string IdToString(int id) { if (id <= 0) { _logger?.LogWarning("尝试获取无效ID的字符串: {Id}", id); return string.Empty; } lock (_lockObject) { IncrementCacheStat("IdToString"); if (id <= _stringList.Count) { IncrementCacheStat("CacheHits"); return _stringList[id - 1]; } IncrementCacheStat("CacheMisses"); _logger?.LogWarning("ID超出范围: {Id}, 最大ID: {MaxId}", id, _stringList.Count); return string.Empty; } } /// /// 批量转换字符串为ID /// 性能优化:批量处理减少锁开销 /// /// 字符串列表 /// 对应的ID列表 public List StringToIdBatch(IEnumerable strings) { if (strings == null) { throw new ArgumentNullException(nameof(strings)); } var results = new List(); lock (_lockObject) { foreach (var str in strings) { results.Add(StringToId(str)); } } _logger?.LogDebug("批量转换字符串为ID,共处理 {Count} 个字符串", results.Count); return results; } /// /// 获取字符串缓存信息 /// /// 缓存信息 public (int CacheSize, int ListSize) GetStringCacheInfo() { lock (_lockObject) { return (_stringIdCache.Count, _stringList.Count); } } #endregion #region 私有辅助方法 /// /// 增加缓存统计计数 /// /// 统计名称 private void IncrementCacheStat(string statName) { if (_cacheStats.ContainsKey(statName)) { _cacheStats[statName]++; } } #endregion } }