Re: Simple Dispose Question

Tech Tip: Click here to run a free scan for Windows Errors and optimize PC performance

From: Jon Skeet [C# MVP] (skeet_at_pobox.com)
Date: 02/24/05


Date: Thu, 24 Feb 2005 07:16:20 -0000

Jeff B. <jsb@community.nospam> wrote:
> If an object implements the IDisposable interface, should I always call the
> Dispose method or is just setting it to null and letting the GC handle it
> sufficient? Here is the pattern I've been using but wasn't sure if it was
> necessary:
>
> DataAdapter da = null;
>
> try {
> // Some logic here...
> } catch (Exception ex) {
> // Some exception handling logic here...
> } finally {
> // Clean up...
> if (da != null) {
> da.Dispose();
> da = null;
> }
>
> Is the above necessary or could I just set da = null in the "finally" clause
> and be good?

An equivalent but simpler solution would be to use the using statement:

using (DataAdapter da = ...)
{
...
}

(You can put a try/catch inside the using statement if you really want
- most of the time you should let exceptions propagate up.)

Relying on the garbage collector to release unmanaged resources is a
very bad idea - there's no guarantee about when it will finalize the
object.

-- 
Jon Skeet - <skeet@pobox.com>
http://www.pobox.com/~skeet
If replying to the group, please do not mail me too


Relevant Pages

  • Re: How to stop garbage collector
    ... In scenarios where resources must be released at a specific time, ... can implement the IDisposable interface, ... implementations of the Dispose method can call methods in the GC ... class to customize the finalization behavior of the garbage collector. ...
    (microsoft.public.dotnet.languages.csharp)
  • Re: netFramwor and Dispose
    ... > It is a member of the IDisposable interface and it used to free ... When dispose method is call what it does? ... > unmanaged resources, you should free that resources ... What is diffrence between finalize and dispose method? ...
    (microsoft.public.dotnet.general)
  • Re: GC Dispose method
    ... > IDisposable interface rather than just adding a Dispose method or calling ... This keyword can be placed around a block of code ...
    (microsoft.public.dotnet.languages.csharp)
  • RE: GC Dispose method
    ... Hi Maxim, ... IDisposable interface rather than just adding a Dispose method or calling the ... MyObject x = new MyObject; ...
    (microsoft.public.dotnet.languages.csharp)