Skip to content

New analyzer to suggest adding IAsyncDisposable #1719

Description

@bricelam

Inside of an IDisposable.Dispose() implementation, if any call to IDisposable.Dispose() has an IAsyncDisposable.DisposeAsync() alternative, this type should also implement IAsyncDisposable.

For example, the following implementation should be flagged.

class MyClass : IDisposable
{
    DbConnection? _connection;

    // ...

    public void Dispose()
    {
        _connection?.Dispose();
        _connection = null;
    }
}

And this code should fix it.

class MyClass : IDisposable, IAsyncDisposable
{
    DbConnection? _connection;

    // ...

    public void Dispose()
    {
        _connection?.Dispose();
        _connection = null;
    }

    public async ValueTask DisposeAsync()
    {
        if (_connection is not null)
        {
            await _connection.DisposeAsync();
            _connection = null;
        }
    }
}

This could be accomplished by adding IAsyncDisposable equivalents to CA1001 (Types that own disposable fields should be disposable) and CA2213 (Disposable fields should be disposed).

It might also be worth creating an equivalent to CA2215 (Dispose methods should call base class dispose).

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions