An open API service indexing awesome lists of open source software.

https://github.com/sharpjs/sharp.disposable

Thread-safe implementation of the .NET Dispose Pattern, plus extras.
https://github.com/sharpjs/sharp.disposable

Last synced: 10 months ago
JSON representation

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

Awesome Lists containing this project

README

          

# Sharp.Disposable

Thread-safe implementation of the [.NET Dispose Pattern](https://docs.microsoft.com/en-us/dotnet/standard/garbage-collection/implementing-dispose), plus extras.

## Status

[![Build](https://github.com/sharpjs/Sharp.Disposable/workflows/Build/badge.svg)](https://github.com/sharpjs/Sharp.Disposable/actions)
[![NuGet](https://img.shields.io/nuget/v/Sharp.Disposable.svg)](https://www.nuget.org/packages/Sharp.Disposable)
[![NuGet](https://img.shields.io/nuget/dt/Sharp.Disposable.svg)](https://www.nuget.org/packages/Sharp.Disposable)

- **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

```csharp
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;
}
}
```