Skip to content

sharpjs/Sharp.Disposable

Repository files navigation

Sharp.Disposable

Thread-safe implementation of the .NET Dispose Pattern, plus extras.

Status

Build NuGet NuGet

  • Stable: in production for years with no reported defects.
  • Tested: 100% coverage by automated tests.
  • Documented: IntelliSense on everything.

Overview

This package provides the following types in the Sharp.Disposable namespace:

Name Description
Disposable Base class for any disposable object.
– Thread-safe; dispose from any thread.
– Guarantees that disposal happens only once.
– Provides an IsDisposed property.
– Provides a RequireNotDisposed() helper method.
DisposableBox Generic, mutable box that can hold a single disposable object.
– The object can be owned or borrowed.
– Disposes an owned object when another is placed in the box.
– Disposes an owned object when the box itself is disposed.
DisposablePool Collects multiple disposable objects, disposing them when the pool itself is disposed.
Finalizer Methods to force object finalization.

Usage

using Sharp.Disposable;

public class Foo : Disposable
{
    private SomeDisposable _bar; // a managed resource

    // ...
    
    protected override bool Dispose(bool managed)
    {
        // Check if already disposed
        if (!base.Dispose(managed))
            // False means nothing happened because already disposed
            return false;

        // Clean up unmanaged resources (like temp files) here
        DeleteTemporaryFiles();

        // Check if doing managed disposal too
        if (managed)
            // Disposed managed resources (other IDisposables) here
            _bar.Dispose();

        // True means disposal happened
        return true;
    }
}

About

Thread-safe implementation of the .NET Dispose Pattern, plus extras.

Resources

License

Stars

Watchers

Forks

Packages

No packages published