DisposingUtility Class

Provides utility methods to handle disposing of objects with a mix of IDisposable and IAsyncDisposable interfaces.

public static class DisposingUtility

Methods

NameDescription
Dispose(object?)Synchronously disposes the specified object.
Dispose(object?[])Synchronously dispose all specified disposable objects.
DisposeAsync(object?)Asynchronously or synchronously disposes the specified object.
DisposeAsync(object?[])Asynchronously dispose all specified disposable objects.

Dispose overloads

Dispose(object?)

Synchronously disposes the specified object.

public static void Dispose(object? obj)
Parameters
obj object?
The object to dispose.
Remarks

If obj implements IDisposable, its IDisposable.Dispose method is called.

Otherwise, if obj implements IAsyncDisposable, its IAsyncDisposable.DisposeAsync method is called and the resulting ValueTask is awaited before this method returns.

Otherwise, or if obj is null, this method returns immediately.

This method will not dispose disposable ref structs.

See also

Dispose(object?[])

Synchronously dispose all specified disposable objects.

public static void Dispose(params object?[] items)
Parameters
items object?[]
The objects to dispose.
Exceptions
ArgumentNullException
items is null.
Remarks

This method calls IEnumerable.DisposeAll on the items array.

This method will not dispose disposable ref structs.

See also

DisposeAsync overloads

DisposeAsync(object?)

Asynchronously or synchronously disposes the specified object.

public static ValueTask DisposeAsync(object? obj)
Parameters
obj object?
The object to dispose.
Returns

ValueTask A ValueTask representing the ongoing operation.

Remarks

If obj implements IAsyncDisposable, it is disposed asynchronously and the returned ValueTask represents the ongoing call to IAsyncDisposable.DisposeAsync.

Otherwise, if obj implements IDisposable, it is disposed synchronously and this method returns a completed ValueTask.

Otherwise, or if obj is null, this method immediately returns a completed ValueTask.

This method will not dispose disposable ref structs.

See also

DisposeAsync(object?[])

Asynchronously dispose all specified disposable objects.

public static ValueTask DisposeAsync(params object?[] items)
Parameters
items object?[]
The objects to dispose.
Returns

ValueTask A ValueTask representing the ongoing operation.

Exceptions
ArgumentNullException
items is null.
Remarks

This method calls IEnumerable.DisposeAllAsync on the items array.

This method will not dispose disposable ref structs.

See also