2

Possible Duplicate:
IDisposable Question

I have written a class and implemented the IDisposable interface.

I implemetned the Dispose method and put a Code Break in the method.

My assumption is it would have been called when the Class went out of scope due to C# Garabage collection.

I want the dispose method to close an unmanaged resource. I thought it would be more elegant than just calling the method LogOff() instead getting it called whenever the method went out of scope?

But it doesn't seem to get called or stop at the code break.

1

5 Answers 5

4

You need to explicitly call Dispose on any objects that implement IDisposable. If you use the using() {} code construct the compiler will automatically call Dispose at the end of the using block.

A good pattern is to also track via a private boolean field whether dispose has been called or not, and if not call it from the objects finalizer (and also call GC.SuppressFinalize() from your Dispose method assuming that you handle all finalization tasks from there also).

5
  • Most classes shouldn't have a finalizer. A finalizer is only useful if an object needs to clean up things which cannot have finalizers of their own (most typically because they are not encapsulated in a derivative of Object). For example, a class which acquires a file handle directly from the operating system will often store it as an integer. The garbage collector isn't going to have any idea that before the integer is abandoned, the file handle it represents needs to be closed. Thus, the class holding that integer has to close the appropriate file in its finalizer.
    – supercat
    Dec 9, 2011 at 14:54
  • Because every class object to which a direct or indirect reference is held by a class with a finalizer will survive at least one more generation of garbage collection than it otherwise would, classes which have finalizers should hold avoid holding references to any objects not actually needed for finalization. If a class which would hold an unmanaged resource also needs to hold references to other objects, the unmanaged resource should usually be split out into its own class, with the main class holding a reference to that wrapper object.
    – supercat
    Dec 9, 2011 at 14:58
  • From a pedantic standpoint, I almost wish finalizers didn't exist. While there are times when it is useful to allow objects to detect that they've been wrongfully abandoned and recover from that situation, it masks the fact that in most cases programs which would result in finalizers running are fundamentally broken and should be fixed.
    – supercat
    Dec 9, 2011 at 14:59
  • If an object holds an unmanaged resource and implements IDisposable I think I would always create a finalizer to clean up those resources if the consumers forgot to call Dispose. Dec 9, 2011 at 17:38
  • Designing a class to work with a finalizer is tricky and involves subtle nuances which, if not handled perfectly, can create Heisenbugs. It's sometimes useful to have a finalizer which logs the fact that Dispose wasn't called, but if one "forgets" to call Dispose the solution isn't to do cleanup in the finalizer but to add the missing Dispose. In any case, objects with finalizers should avoid holding direct or indirect strong references to any managed objects not needed for finalization.
    – supercat
    Dec 9, 2011 at 17:58
2

You should consider wrapping your interaction with your IDisposable class in a using statement. Doing so will allow you to specify when your object goes out of scope, and ensures the Dispose() method gets called.

For the correct syntax, see the example from the referenced MSDN article:

using System;

class C : IDisposable
{
    public void UseLimitedResource()
    {
        Console.WriteLine("Using limited resource...");
    }

    void IDisposable.Dispose()
    {
        Console.WriteLine("Disposing limited resource.");
    }
}

class Program
{
    static void Main()
    {
        using (C c = new C())
        {
            c.UseLimitedResource();
        }
        Console.WriteLine("Now outside using statement.");
        Console.ReadLine();
    }
}
1

Short answer: Dispose() is called when you call it.

Long answer: take a look at using block. This is a syntax sugar that meant to be used together with IDisposable interface for pretty and safely disposing code, and is roughly equivalent to

Foo foo = new Foo();
try
{
    // your code that uses foo
}
finally
{
    foo.Dispose();
}

In other words foo is guaranteed to be disposed upon leaving using() scope.

0

Garbage collection does not happen immediately after a variable goes out of scope. The GC runs periodically and .NET has different "levels" of Garbage collection. Different levels get collected more frequently. If you want your object's dispose method to be called immediately, you should use a using statement

using (MyClass object = new MyClass())
{
//ensures Dipose is called, even if exceptions are thrown
}
0
My assumption is it would have been called when the Class went out of scope due to C# Garabage collection.

That's now how garbage collection works. There's two things going on here:

Garbage collection - this cleans up objects at some time after there's no longer any references left to them. This implies that the objects have gone out of scope (if they are locals), but notably GC doesn't say when this cleanup happens - it usually happens lazily when the system decides it needs to run a collection to free up more memory. The method that is called to clean up resources in this case is the finalizer, which in C# has the form ~Classname().

IDisposable: the problem with GC is that you have no control over when the finalizer is called, so IDisposable was introduced as a pattern to be used when you need resources to be cleaned up at a specific time and don't want to wait for a collect to happen. It's up to the caller code to call Dispose() as appropriate, there's no GC support. C# does have the using(){} syntax, which simplifies this, and calls Dispose() automatically at the end of the using block.

Not the answer you're looking for? Browse other questions tagged or ask your own question.