using System; using System.Collections.Generic; using System.Text; namespace Thousandto.Core.Base { /// /// PooledObject base calss /// public abstract class PooledObject : IDisposable { #region Internal Properties /// /// Internal Action that is initialized by the pool while creating the object, this allow that object to re-add itself back to the pool. /// internal MyAction ReturnToPool { get; set; } /// /// Internal flag that is being managed by the pool to describe the object state - primary used to void cases where the resources are being releases twice. /// internal bool Disposed { get; set; } #endregion #region Internal Methods - resource and state management /// /// 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 being destroyed) /// /// internal bool ReleaseResources() { bool successFlag = true; try { OnReleaseResources(); } catch ( Exception ) { successFlag = false; } return successFlag; } /// /// Reset the object state /// This method will be called by the pool manager just before the object is being returned to the pool /// /// internal bool ResetState() { bool successFlag = true; try { OnResetState(); } catch ( Exception ) { successFlag = false; } return successFlag; } #endregion #region Virtual Template Methods - extending resource and state management /// /// Reset the object state to allow this object to be re-used by other parts of the application. /// protected virtual void OnResetState() { } /// /// Releases the object's resources /// protected virtual void OnReleaseResources() { } #endregion #region Returning object to pool - Dispose and Finalizer private void HandleReAddingToPool( bool reRegisterForFinalization ) { if ( !Disposed ) { // If there is any case that the re-adding to the pool failes, release the resources and set the internal Disposed flag to true try { // Notifying the pool that this object is ready for re-adding to the pool. ReturnToPool( this, reRegisterForFinalization ); } catch ( Exception ) { Disposed = true; this.ReleaseResources(); } } } ~PooledObject() { // Resurrecting the object HandleReAddingToPool( true ); } public void Dispose() { // Returning to pool HandleReAddingToPool( false ); } #endregion } }