浅谈Pool对象
Pool對象的技術指標:
避免頻繁創建經常使用的稀有資源,提高工作效率.
控制閥值,很多情況下一些關鍵資源都有一個最佳并發數,超過這個拐點性能有可能急劇下降,也有可能繼續增大并發數性能不能提升.
安全的獲取對象和釋放對象(使用之后放回連接池)
public sealed class Pool<T> : IDisposable where T : IDisposable
{
private bool disposed = false;
private Semaphore gate;
private Stack<T> pool;
public event Predicate<T> Predicate;
public Pool(int concrrent,Func<Pool<T>,T> activator)
{
if (concrrent <= 0)
{
throw new ArgumentException("concrrent");
}
if (activator==null)
{
throw new ArgumentNullException("activator");
}
gate = new Semaphore(concrrent, concrrent);
pool = new Stack<T>();
for (int i=0;i< concrrent; i++)
{
pool.Push(activator(this));
}
}
public T Acquire()
{
if (!gate.WaitOne())
throw new InvalidOperationException();
lock (pool)
{
return pool.Pop();
}
}
public void Release(T target)
{
lock (pool)
{
if (Predicate!=null)
{
if (Predicate(target))
{
pool.Push(target);
gate.Release();
}
}
else
{
if (target != null)
{
pool.Push(target);
gate.Release();
}
}
}
}
private void Dispose(bool disposing)
{
if (disposed)
return;
if (disposing)
{
gate.Dispose();
}
for (int i = 0; i < pool.Count; i++)
{
var t = pool.Pop();
t.Dispose();
}
disposed = true;
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
~Pool()
{
Dispose(false);
}
}
T對象實現時最好與Pool對象建立某種關聯,調用T對象實例的某個方法時可以將對象送回Pool,而不是銷毀它.同時Pool對象Release對象時,最好通過事件(關聯關系)判斷是否是從Pool對象獲取的,然后放回Pool.
總結
- 上一篇: 表达自己自谦的句子
- 下一篇: 咖啡豆和可可豆(咖啡豆怎么来的)