com.alicizax.unity.framework/Runtime/UI/Manager/UIService.Cache.cs
陈思海 cd5de2c374 优化UIService模块
优化UI模块更多细节容错处理 优化UI模块内存泄露问题 优化性能
2026-04-23 20:19:46 +08:00

96 lines
2.8 KiB
C#

using System;
using System.Collections.Generic;
using AlicizaX;
namespace AlicizaX.UI.Runtime
{
internal sealed partial class UIService
{
private readonly struct CacheEntry
{
public readonly UIMetadata Metadata;
public readonly int TimerId;
public CacheEntry(UIMetadata metadata, int timerId)
{
Metadata = metadata;
TimerId = timerId;
}
}
private readonly Dictionary<RuntimeTypeHandle, CacheEntry> m_CacheWindow = new();
private void CacheWindow(UIMetadata uiMetadata, bool force)
{
if (uiMetadata?.View?.Holder == null)
{
Log.Error("Cannot cache null UI metadata or holder");
return;
}
if (force || uiMetadata.MetaInfo.CacheTime == 0)
{
uiMetadata.Dispose();
return;
}
RemoveFromCache(uiMetadata.MetaInfo.RuntimeTypeHandle);
int timerId = -1;
uiMetadata.View.Holder.transform.SetParent(UICacheLayer);
if (uiMetadata.MetaInfo.CacheTime > 0)
{
ITimerService timerService = GetTimerService();
timerId = timerService.AddTimer(
OnTimerDisposeWindow,
uiMetadata,
uiMetadata.MetaInfo.CacheTime,
isLoop: false,
isUnscaled: true
);
if (timerId <= 0)
{
Log.Warning($"Failed to create cache timer for {uiMetadata.UILogicType.Name}");
}
}
uiMetadata.InCache = true;
m_CacheWindow.Add(uiMetadata.MetaInfo.RuntimeTypeHandle, new CacheEntry(uiMetadata, timerId));
}
private void OnTimerDisposeWindow(UIMetadata meta)
{
if (meta != null)
{
RemoveFromCache(meta.MetaInfo.RuntimeTypeHandle);
meta.Dispose();
}
}
private void RemoveFromCache(RuntimeTypeHandle typeHandle)
{
if (m_CacheWindow.TryGetValue(typeHandle, out var entry))
{
m_CacheWindow.Remove(typeHandle);
entry.Metadata.InCache = false;
if (entry.TimerId > 0 && _timerService != null)
{
_timerService.RemoveTimer(entry.TimerId);
}
}
}
private ITimerService GetTimerService()
{
if (_timerService != null)
{
return _timerService;
}
_timerService = AppServices.Require<ITimerService>();
return _timerService;
}
}
}