Wrong usage with IDisposable

Jun 7, 2015 at 3:49 AM
Be aware of subscribing to IDisposable or use IDisposable in lambda:
internal class Foo : IDisposable
{  
    EventMessageHandler h;
    EventMessageHandler h2;
    EventMessageHandler h3;
    private object obj = new object();
    
    ~Foo()
    {
        h.Dispose();
        h2.Dispose();
        h3.Dispose();
        Console.WriteLine("finalized" + N);
    }

    public void Dispose()
    {
        h.Dispose();
        h2.Dispose();
        h3.Dispose();
        Console.WriteLine("disposed" + N);
    }
    
    public void Subscribe()
    {
        // wrong - this captured by EventAggregator as eventSource and never finalized
        h = this.Subscribe(0, null);
        
        // my approach to solve
        h2 = obj.Subscribe(0, null);
        
        // wrong - this captured by closure
        h3 = obj.Subscribe(0, (e) =>
        {
            Console.WriteLine(this);
        });
    }
}