89 lines
2.6 KiB
Markdown
89 lines
2.6 KiB
Markdown
|
|
# ResourceCache
|
|||
|
|
|
|||
|
|
**命名空间**: `XCEngine::Resources`
|
|||
|
|
|
|||
|
|
**类型**: `class`
|
|||
|
|
|
|||
|
|
**头文件**: `XCEngine/Core/Asset/ResourceCache.h`
|
|||
|
|
|
|||
|
|
**描述**: 资源缓存管理器,实现 LRU(最近最少使用)淘汰策略的资源缓存。
|
|||
|
|
|
|||
|
|
## 概述
|
|||
|
|
|
|||
|
|
`ResourceCache` 维护了一个内存资源缓存,使用 LRU 策略管理资源条目。当内存使用超过预算时,会自动淘汰最近最少使用的资源。
|
|||
|
|
|
|||
|
|
## 公共方法
|
|||
|
|
|
|||
|
|
### 缓存操作
|
|||
|
|
|
|||
|
|
| 方法 | 描述 |
|
|||
|
|
|------|------|
|
|||
|
|
| `void Add(ResourceGUID guid, IResource* resource)` | 添加资源到缓存 |
|
|||
|
|
| `void Remove(ResourceGUID guid)` | 从缓存移除资源 |
|
|||
|
|
| `IResource* Find(ResourceGUID guid) const` | 查找缓存中的资源 |
|
|||
|
|
| `void Touch(ResourceGUID guid)` | 更新资源的访问时间 |
|
|||
|
|
|
|||
|
|
### 缓存信息
|
|||
|
|
|
|||
|
|
| 方法 | 描述 |
|
|||
|
|
|------|------|
|
|||
|
|
| `size_t GetSize() const` | 获取缓存条目数量 |
|
|||
|
|
| `size_t GetMemoryUsage() const` | 获取缓存内存使用量(字节) |
|
|||
|
|
|
|||
|
|
### 内存管理
|
|||
|
|
|
|||
|
|
| 方法 | 描述 |
|
|||
|
|
|------|------|
|
|||
|
|
| `void SetMemoryBudget(size_t bytes)` | 设置内存预算 |
|
|||
|
|
| `size_t GetMemoryBudget() const` | 获取内存预算 |
|
|||
|
|
| `void OnMemoryPressure(size_t requiredBytes)` | 内存压力回调,淘汰资源释放内存 |
|
|||
|
|
| `void OnZeroRefCount(ResourceGUID guid)` | 引用计数归零时的回调 |
|
|||
|
|
|
|||
|
|
### 缓存刷新
|
|||
|
|
|
|||
|
|
| 方法 | 描述 |
|
|||
|
|
|------|------|
|
|||
|
|
| `void Flush()` | 刷新所有缓存资源 |
|
|||
|
|
| `void Clear()` | 清空缓存 |
|
|||
|
|
|
|||
|
|
### LRU 操作
|
|||
|
|
|
|||
|
|
| 方法 | 描述 |
|
|||
|
|
|------|------|
|
|||
|
|
| `Containers::Array<ResourceGUID> GetLRUList(size_t count) const` | 获取最近最少使用的资源 GUID 列表 |
|
|||
|
|
|
|||
|
|
## 实现说明
|
|||
|
|
|
|||
|
|
**LRU 策略**: 缓存使用 LRU(Least Recently Used)策略淘汰资源。当 `OnMemoryPressure()` 被调用时,会从最近最少使用的资源开始淘汰,直到释放足够的内存。
|
|||
|
|
|
|||
|
|
**线程安全**: 缓存操作通过互斥锁保护,部分只读操作使用读锁以提高并发性能。
|
|||
|
|
|
|||
|
|
## 使用示例
|
|||
|
|
|
|||
|
|
```cpp
|
|||
|
|
#include <XCEngine/Core/Asset/ResourceCache.h>
|
|||
|
|
|
|||
|
|
using namespace XCEngine::Resources;
|
|||
|
|
|
|||
|
|
// 获取缓存实例(ResourceManager 内部使用)
|
|||
|
|
ResourceCache& cache = /* ... */;
|
|||
|
|
|
|||
|
|
// 设置内存预算 256MB
|
|||
|
|
cache.SetMemoryBudget(256 * 1024 * 1024);
|
|||
|
|
|
|||
|
|
// 手动触发内存压力释放
|
|||
|
|
cache.OnMemoryPressure(50 * 1024 * 1024); // 释放 50MB
|
|||
|
|
|
|||
|
|
// 获取 LRU 列表
|
|||
|
|
auto lruItems = cache.GetLRUList(10);
|
|||
|
|
for (const auto& guid : lruItems) {
|
|||
|
|
// 处理每个 LRU 条目
|
|||
|
|
}
|
|||
|
|
```
|
|||
|
|
|
|||
|
|
## 相关文档
|
|||
|
|
|
|||
|
|
- [ResourceManager](resource-manager/resource-manager.md) - 资源管理器
|
|||
|
|
- [IResource](iresource/iresource.md) - 资源基类
|
|||
|
|
- [Resources 总览](resources.md) - 返回模块总览
|