Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

IDISP011 False positive when .Dispose is called in an event handler #571

Open
hwndmaster opened this issue May 16, 2024 · 2 comments
Open

Comments

@hwndmaster
Copy link

IDisposableAnalyzers version: 4.0.7

I have a scenario similar to this:

using System.Reactive;
using System.Reactive.Subjects;

namespace Demo;

internal sealed class Test
{
    private IObservable<Unit> _eventTriggered = new Subject<Unit>();

    public void Run()
    {
        using var foo = CreateFoo();
        // ...
    }

    private Foo CreateFoo()
    {
        var foo = new Foo();
        _eventTriggered.Subscribe(_ =>
        {
            // If the following line is commented, then no report of IDISP011:
            foo.Dispose();
        });
        return foo; // IDISP011: Don't return disposed instance
    }

    sealed class Foo : IDisposable
    {
        public void Dispose() { /* ... */ }
    }
}

foo can be disposed in two places: by the owner (for example, inside Run() method), or by some event, triggered somewhere else.

N.B.: Ignore other reports of IDISP004 or IDISP008, this is an example for IDISP011 only.

@manfred-brands
Copy link

Why Dispose it in the .Subscribe if it has to be disposed anyhow.
What if the Observable doesn't fire (or fires multiple times)?

@hwndmaster
Copy link
Author

Why Dispose it in the .Subscribe if it has to be disposed anyhow. What if the Observable doesn't fire (or fires multiple times)?

Observable is an optional route in my case (particularly, it handles item removal from the list, if requested by a user), and normally the item is being disposed when the owner disposes the list where all Foos are contained.

Disposing the same item multiple times isn't a problem, since

  1. the owner got notified about its item disposal and then it removes it from its list
  2. the disposal method is safe for calling it multiple times. In my case it has IsDisposed flag to handle that.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants