changeset 83:397fe8db0806 v2

fixed object pool
author cin
date Mon, 29 Sep 2014 15:49:15 +0400
parents 0363407ee75c
children 34bb2f32634d
files Implab/ObjectPool.cs
diffstat 1 files changed, 16 insertions(+), 9 deletions(-) [+]
line wrap: on
line diff
--- a/Implab/ObjectPool.cs	Mon Sep 29 05:04:32 2014 +0400
+++ b/Implab/ObjectPool.cs	Mon Sep 29 15:49:15 2014 +0400
@@ -9,9 +9,9 @@
         readonly int m_size;
         readonly MTQueue<T> m_queue = new MTQueue<T>();
 
-        volatile bool m_disposed;
+        bool m_disposed;
 
-        volatile int m_count;
+        int m_count;
 
         public ObjectPool(Func<T> factory, Action<T> cleanup, int size) {
             Safe.ArgumentNotNull(factory, "factory");
@@ -28,21 +28,26 @@
         public ObjectPool(Func<T> factory) : this(factory,null,Environment.ProcessorCount+1) {
         }
 
-        public ObjectPoolWrapper<T> Allocate() {
+        public ObjectPoolWrapper<T> AllocateAuto() {
+
+            return new ObjectPoolWrapper<T>(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<T>(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 @@
                 // и возможно уже законцена, в таком случае следует извлечь элемент обратно и
                 // освободить его. Если операция освобождения кеша еще не заврешилась, то будет
                 // изъят и освобожден произвольный элемен, что не повлияет на ход всего процесса.
-                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 @@
                 m_disposed = true;
                 T instance;
                 while (m_queue.TryDequeue(out instance))
-                    Safe.Dispose(instance);
+                    if (instance is IDisposable)
+                        ((IDisposable)instance).Dispose();
             }
         }