You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
69 lines
1.6 KiB
69 lines
1.6 KiB
using System; |
|
using System.Collections.Generic; |
|
|
|
namespace AX.Common |
|
{ |
|
public class ObjectPool<T> |
|
{ |
|
private Queue<T> queue; |
|
private Func<T> creator; |
|
private Action<T> clearer; |
|
|
|
public int AvailableCount { get { return this.queue.Count; } } |
|
|
|
public ObjectPool(int initialCount, Func<T> creator, Action<T> clearer = null) |
|
{ |
|
if (initialCount < 0) |
|
throw new ArgumentOutOfRangeException("initialCount"); |
|
|
|
if (creator == null) |
|
throw new ArgumentNullException("creator"); |
|
|
|
this.queue = new Queue<T>(initialCount); |
|
|
|
this.creator = creator; |
|
this.clearer = clearer; |
|
} |
|
|
|
/// <summary> |
|
/// 从对象池获得一个对象实例。 |
|
/// </summary> |
|
public T Acquire() |
|
{ |
|
if (queue.Count != 0) |
|
return queue.Dequeue(); |
|
|
|
return creator(); |
|
} |
|
|
|
/// <summary> |
|
/// 把指定的对象实例归还对象池。 |
|
/// </summary> |
|
public void Release(T obj) |
|
{ |
|
if (clearer != null) |
|
clearer(obj); |
|
|
|
queue.Enqueue(obj); |
|
} |
|
|
|
public void Clear() |
|
{ |
|
if (typeof(T) == typeof(IDisposable)) |
|
{ |
|
while (queue.Count != 0) |
|
{ |
|
var obj = queue.Dequeue(); |
|
|
|
((IDisposable)obj).Dispose(); |
|
} |
|
} |
|
else |
|
{ |
|
queue.Clear(); |
|
} |
|
|
|
queue.TrimExcess(); |
|
} |
|
} |
|
} |