0

Possible Duplicate:
Proper use of the IDisposable interface
When is Dispose necessary?

If I write a class, which uses graphics, or threads for example, must I implement the IDisposable interface to write a Dispose() method or else memory leak occurs? Does Dipose() run when the GC reaches it? If I implement a Dispose() method, shall I call Dispose() on all the disposable fields in the class when "disposing" parameter is true, or is it automatic? What is "unmanaged resource"?

So I'm pretty unsure about it, I'd appreciate anything that helps me understand these things :) Thank You

Community
  • 1
  • 1
  • 2
    This must be about the most written-about subject in .NET programming. – Igby Largeman Sep 06 '11 at 18:34
  • 1
    @KisGabo isn't SO suggesting you similar questions when you enter the title of a new question? I thought that auto suggest was working cross browser including yours :) – Davide Piras Sep 06 '11 at 18:35
  • The [cannon examples from Microsoft](http://msdn.microsoft.com/en-us/library/system.idisposable.dispose.aspx) all show implementing Dispose with a finalizer. Of course, bear in mind that `using` (aka `Dispose()`) is best because the GC and finalizers are somewhat non-deterministic -- note nothing wrt IDisposable is "automatic" –  Sep 06 '11 at 18:36

1 Answers1

0

IDisposable is just a pattern to follow. It doesn't do anything, in and of itself, special (other than fitting the requirements of the using statement).

If you're working with a native resource, the resource isn't "known" to the garbage collector. IDisposable is the convention used to allow you to free this resource deterministically.

For details, I wrote a detailed series on IDisposable which talks about why and how to implement it for various scenarios (including wrapping a native resource, encapsulating other IDispsable types, etc).

Reed Copsey
  • 554,122
  • 78
  • 1,158
  • 1,373