Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

IDisposable Question

Tags:

c#

Say I have the following:

public abstract class ControlLimitBase : IDisposable 
{
}

public abstract class UpperAlarmLimit : ControlLimitBase 
{
}

public class CdsUpperAlarmLimit : UpperAlarmLimit 
{
}

Two Questions:

1. I'm a little confused on when my IDisposable members would actually get called. Would they get called when an instance of CdsUpperAlarmLimit goes out of scope?

2. How would I handle disposing of objects created in the CdsUpperAlarmLimit class? Should this also derive from IDisposable?

like image 530
Hosea146 Avatar asked Sep 15 '11 16:09

Hosea146


2 Answers

Dispose() is never called automatically - it depends on how the code is actually used.

1.) Dispose() is called when you specifically call Dispose():

myAlarm.Dispose();

2.) Dispose() is called at the end of a using block using an instance of your type.

using(var myAlarm = new CdsUpperAlarmLimit())
{

}

The using block is syntactic sugar for a try/finally block with a call to Dispose() on the object "being used" in the finally block.

like image 92
BrokenGlass Avatar answered Nov 15 '22 13:11

BrokenGlass


  1. No, IDisposable won't be called just automatically. You'd normally call Dispose with a using statement, like this:

    using (ControlLimitBase limit = new UpperAlarmLimit())
    {
        // Code using the limit
    }
    

    This is effectively a try/finally block, so Dispose will be called however you leave the block.

  2. CdsUpperAlarmLimit already implements IDisposable indirectly. If you follow the normal pattern for implementing IDisposable in non-sealed classes, you'll override void Dispose(bool disposing) and dispose your composed resources there.

Note that the garbage collector does not call Dispose itself - although it can call a finalizer. You should rarely use a finalizer unless you have a direct handle on unmanaged resources though.

To be honest, I usually find it's worth trying to change the design to avoid needing to keep hold of unmanaged resources in classes - implementing IDisposable properly in the general case is frankly a pain. It's not so bad if your class is sealed (no need for the extra method; just implement the Dispose() method) - but it still means your clients need to be aware of it, so that they can use an appropriate using statement.

like image 30
Jon Skeet Avatar answered Nov 15 '22 14:11

Jon Skeet