diff --git a/src/CodeProject.ObjectPool/ObjectPool.cs b/src/CodeProject.ObjectPool/ObjectPool.cs index 96b6050..58d0cd2 100644 --- a/src/CodeProject.ObjectPool/ObjectPool.cs +++ b/src/CodeProject.ObjectPool/ObjectPool.cs @@ -177,24 +177,29 @@ public void Clear() /// A monitored object from the pool. public T GetObject() { - if (PooledObjects.TryDequeue(out T pooledObject)) + while (true) { - // Object found in pool. - if (Diagnostics.Enabled) Diagnostics.IncrementPoolObjectHitCount(); - } - else - { - // This should not happen normally, but could be happening when there is stress on - // the pool. No available objects in pool, create a new one and return it to the caller. - if (Diagnostics.Enabled) Diagnostics.IncrementPoolObjectMissCount(); - pooledObject = CreatePooledObject(); - } - - // Change the state of the pooled object, marking it as reserved. We will mark it as - // available as soon as the object will return to the pool. - pooledObject.PooledObjectInfo.State = PooledObjectState.Reserved; + if (PooledObjects.TryDequeue(out T pooledObject)) + { + // Object found in pool. + if (Diagnostics.Enabled) Diagnostics.IncrementPoolObjectHitCount(); + } + else + { + // This should not happen normally, but could be happening when there is stress on + // the pool. No available objects in pool, create a new one and return it to the caller. + if (Diagnostics.Enabled) Diagnostics.IncrementPoolObjectMissCount(); + pooledObject = CreatePooledObject(); + } + if (pooledObject.ValidateObject()) + { + // Change the state of the pooled object, marking it as reserved. We will mark it as + // available as soon as the object will return to the pool. + pooledObject.PooledObjectInfo.State = PooledObjectState.Reserved; - return pooledObject; + return pooledObject; + } + } } void IObjectPoolHandle.ReturnObjectToPool(PooledObject objectToReturnToPool, bool reRegisterForFinalization) diff --git a/src/CodeProject.ObjectPool/PooledObject.cs b/src/CodeProject.ObjectPool/PooledObject.cs index 1ceb2b4..53efa27 100644 --- a/src/CodeProject.ObjectPool/PooledObject.cs +++ b/src/CodeProject.ObjectPool/PooledObject.cs @@ -46,6 +46,15 @@ public abstract class PooledObject : EquatableObject, IDisposable #region Internal Methods - resource and state management + /// + /// Validate wraped Object state. + /// + /// + internal virtual bool ValidateObject() + { + return true; + } + /// /// Releases the object resources. This method will be called by the pool manager when /// there is no need for this object anymore (decreasing pooled objects count, pool is