com.alicizax.unity.framework/Runtime/ABase/Base/MemoryPool/MemoryPoolExtension.cs

55 lines
1.3 KiB
C#
Raw Normal View History

2026-04-21 14:24:36 +08:00
using System;
2025-10-11 15:18:09 +08:00
namespace AlicizaX
{
/// <summary>
/// 内存池对象基类。
/// </summary>
public abstract class MemoryObject : IMemory
{
/// <summary>
/// 清理内存对象回收入池。
/// </summary>
public virtual void Clear()
{
}
/// <summary>
/// 从内存池中初始化。
/// </summary>
public abstract void InitFromPool();
/// <summary>
/// 回收到内存池。
/// </summary>
public abstract void RecycleToPool();
}
public static partial class MemoryPool
{
/// <summary>
/// 从内存池获取内存对象。
/// </summary>
public static T Alloc<T>() where T : MemoryObject, new()
{
2026-04-21 14:24:36 +08:00
T memory = MemoryPool<T>.Acquire();
2025-10-11 15:18:09 +08:00
memory.InitFromPool();
return memory;
}
/// <summary>
/// 将内存对象归还内存池。
/// </summary>
public static void Dealloc(MemoryObject memory)
{
if (memory == null)
{
2026-04-21 14:24:36 +08:00
throw new ArgumentNullException(nameof(memory));
2025-10-11 15:18:09 +08:00
}
memory.RecycleToPool();
2026-04-21 14:24:36 +08:00
MemoryPoolRegistry.Release(memory);
2025-10-11 15:18:09 +08:00
}
}
}