对象内存池,内存池,对象池,MemoryPool

在堆栈的基础上实现对象内存池的管理。

函数定义

public class MemoryPool where T: new() { // Fields private Stack _items; private object _sync; // Methods public MemoryPool(); public T Pop(); public T PopExist(); public Queue Pops(int count); public bool Push(T item, [Optional, DefaultParameterValue(0x3e8)] int max); // Properties public int Count { get; } } public MemoryPool() { this._items = new Stack(); this._sync = new object(); } //堆栈弹出 public T Pop() { object obj2 = this._sync; lock (obj2) { if (this._items.Count == 0) { return Activator.CreateInstance(); } return this._items.Pop(); } } public T PopExist() { object obj2 = this._sync; lock (obj2) { if (this._items.Count == 0) { return default(T); } return this._items.Pop(); } } public Queue Pops(int count) { Queue queue = new Queue(count); object obj2 = this._sync; lock (obj2) { for (int i = 0; i < count; i++) { if (this._items.Count == 0) { queue.Enqueue(Activator.CreateInstance()); } else { queue.Enqueue(this._items.Pop()); } } } return queue; } public bool Push(T item, [Optional, DefaultParameterValue(0x3e8)] int max) { if (this._items.Count >= max) { return false; } object obj2 = this._sync; lock (obj2) { if (this._items.Count >= max) { return false; } if (item is IMemoryPool) { ((IMemoryPool) item).InitMemoryPool(); } this._items.Push(item); } return true; } public int Count { get { return this._items.Count; } }
(0)

相关推荐