# HG changeset patch # User cin # Date 2014-09-29 11:49:15 # Node ID 397fe8db0806aca89c7c1094c10875f06d745ce5 # Parent 0363407ee75c3b0abb87eeefba68799d665c2d1b fixed object pool diff --git a/Implab/ObjectPool.cs b/Implab/ObjectPool.cs --- a/Implab/ObjectPool.cs +++ b/Implab/ObjectPool.cs @@ -9,9 +9,9 @@ namespace Implab { readonly int m_size; readonly MTQueue m_queue = new MTQueue(); - volatile bool m_disposed; + bool m_disposed; - volatile int m_count; + int m_count; public ObjectPool(Func factory, Action cleanup, int size) { Safe.ArgumentNotNull(factory, "factory"); @@ -28,21 +28,26 @@ namespace Implab { public ObjectPool(Func factory) : this(factory,null,Environment.ProcessorCount+1) { } - public ObjectPoolWrapper Allocate() { + public ObjectPoolWrapper AllocateAuto() { + + return new ObjectPoolWrapper(Allocate(), this); + } + + public T Allocate() { if (m_disposed) throw new ObjectDisposedException(this.ToString()); T instance; if (m_queue.TryDequeue(out instance)) { Interlocked.Decrement(ref m_count); - return instance; } else { instance = m_factory(); } - return new ObjectPoolWrapper(instance, this); + return instance; } public void Release(T instance) { + Thread.MemoryBarrier(); if (m_count < m_size && !m_disposed) { Interlocked.Increment(ref m_count); @@ -55,11 +60,12 @@ namespace Implab { // и возможно уже законцена, в таком случае следует извлечь элемент обратно и // освободить его. Если операция освобождения кеша еще не заврешилась, то будет // изъят и освобожден произвольный элемен, что не повлияет на ход всего процесса. - if (m_disposed && m_queue.TryDequeue(out instance)) - Safe.Dispose(instance); + if (m_disposed && m_queue.TryDequeue(out instance) && instance is IDisposable) + ((IDisposable)instance).Dispose() ; } else { - Safe.Dispose(instance); + if (instance is IDisposable) + ((IDisposable)instance).Dispose(); } } @@ -68,7 +74,8 @@ namespace Implab { m_disposed = true; T instance; while (m_queue.TryDequeue(out instance)) - Safe.Dispose(instance); + if (instance is IDisposable) + ((IDisposable)instance).Dispose(); } }