ReferenceCountedDisposableBase - Yortw/Yort.Trashy GitHub Wiki

Purpose

Sometimes managing the lifetime of an object can be difficult. Other components may dispose an instance when they don't own it, or an instance may have multiple owners and deciding when to dispose it may be awkward. The ReferenceCountedDisposableBase helps by keeping track of the number of references to the instance via calls to it's AddReference method. Each call to Dispose decrements the reference count by one without disposing the object, until the reference count reaches zero at which point the dispose method will actually dispose the object. The reference count for a newly created object inheriting from ReferenceCountedDisposableBase is 1, so AddReference need only be called for/by owners other than the initial creator.

Implementing ReferenceCountedDisposableBase

Inherit from the base class, and override DisposeManagedResources and/or DisposeUnmanagedResources when you should perform your actual dispose logic. All of the referece counting related implementation is taken care of for you in the base class.

    public class MyDisposable : ReferenceCountedDisposableBase
    {
        private System.IO.Stream _Stream;

        public MyDisposable(System.IO.Stream stream)
        {
            _Stream = stream;
        }

        protected overrde void DisposeManagedResources()
        {
            _Stream.TryDispose();
        }
    }

Using a Reference Counted MyDisposable


    var disposable = new MyDisposable(new System.IO.MemoryStream());
    // Disposable will have one reference at this point

    // Add another reference to prevent early disposable
    disposable.AddReference();

    //Call dispose to decrement the reference count, the object still
    //won't be disposed because it has two references.
    disposable.TryDispose();

    //Calling dispose a second time will reduce the count to 0, and 
    //actually dispose object.
    disposable.TryDispose();