473,387 Members | 1,435 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,387 software developers and data experts.

Simple Dispose Question

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?

--- Thanks, Jeff

--

Jeff Bramwell
Digerati Technologies, LLC
www.digeratitech.com

Manage Multiple Network Configurations with Select-a-Net
www.select-a-net.com
Nov 16 '05 #1
12 4365
Hi Jeff,

If a class has a Dispose method the best practice is to call it. the reason
behind that is that Dispose runs when called, whereas setting the object to
null simply adds a entry to the Finalize queue in GC, and we cannot
determine when GC will run.

HTH,
Telmo Sampaio
MCT
"Jeff B." <js*@community.nospam> wrote in message
news:ed**************@TK2MSFTNGP14.phx.gbl...
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?

--- Thanks, Jeff

--

Jeff Bramwell
Digerati Technologies, LLC
www.digeratitech.com

Manage Multiple Network Configurations with Select-a-Net
www.select-a-net.com

Nov 16 '05 #2
Setting da to null isn't really necessary, the GC is intelligent enough
to know that there are no more references. Calling Dispose() has
nothing to do with GC either.

Calling Dispose() is recommended for the simple reason that the
resources held by that class get released earlier (it does *not* mean
the object will get GCed immediately). It also prevents the object from
being added to the finalization queue and getting finalized, which can
delay the GCing of the object.

Regards
Senthil

Nov 16 '05 #3
Hi Jeff,

I agree with Senthil. The Dispose method is often used to dispose unmanaged
resources that the object uses. What I recommend is not to call it, but
just leave it to GC. HTH.

Kevin Yu
=======
"This posting is provided "AS IS" with no warranties, and confers no
rights."

Nov 16 '05 #4
Jeff B. <js*@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 - <sk***@pobox.com>
http://www.pobox.com/~skeet
If replying to the group, please do not mail me too
Nov 16 '05 #5
Jeff,
I'd like to add something that hasn't come out in this thread yet. The
use of .Dispose() has been thoroughly discussed, but I'd like to answer
your question regarding the benefit of additionally setting the
variable to null.

If I assume that you have a method containing only that code:
void Foo(){
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;
}
}
you are setting da to null one statement before it would naturally be
set to null (or go out of scope). At the end of every method, every
variable declared in the method is set to null and goes out of scope,
so there is no benefit of explicitly setting it to null because it will
automatically happen one statement later.

On the other hand, there are situations where if may be beneficial to
set this to null. For instance:
void Foo(){
DataAdapter da = new DataAdapter(. . .);
try{
// use it somehow
}finally{
da.Dispose();
}
// now call another method that may take a while to return
}
Here, we would wait for another long-running method to return and the
da variable would still be in scope. Depending on what the
long-running method does, the GC may run several times. IN THIS CASE,
if you set da to null just before calling the long-running method, any
garbase collections would be able to reclaim that memory, and you would
have a benefit.

Normally, my methods are small enough that my variables naturally go
out of scope quickly, but in cases where they might not, set it to
null.

Best regards,
Jeffrey Palermo
Blog: http://www.jeffreypalermo.com

Nov 16 '05 #6
Jeffrey Palermo, MCAD.Net <je************@gmail.com> wrote:

<snip>
On the other hand, there are situations where if may be beneficial to
set this to null. For instance:
void Foo(){
DataAdapter da = new DataAdapter(. . .);
try{
// use it somehow
}finally{
da.Dispose();
}
// now call another method that may take a while to return
}
Here, we would wait for another long-running method to return and the
da variable would still be in scope. Depending on what the
long-running method does, the GC may run several times. IN THIS CASE,
if you set da to null just before calling the long-running method, any
garbase collections would be able to reclaim that memory, and you would
have a benefit.


Actually, in most cases there's still no benefit - in release mode, the
JIT notices that the variable is never read again, and makes it
eligible for collection even before it goes out of scope.

--
Jon Skeet - <sk***@pobox.com>
http://www.pobox.com/~skeet
If replying to the group, please do not mail me too
Nov 16 '05 #7
Kevin Yu [MSFT] <v-****@online.microsoft.com> wrote:
I agree with Senthil. The Dispose method is often used to dispose unmanaged
resources that the object uses. What I recommend is not to call it, but
just leave it to GC. HTH.


That way you end up with hard-to-diagnose problems where, say, one
stream has finished writing to a file, but the stream hasn't been
finalized. An attempt to open the file for reading would then fail -
but on another run it might succeed, because the garbage collector
might have finalized the writing stream earlier.

In another situation, with a databasse connection, you might end up
running out of pooled connections even though they're not actually
being used by anything any more.

In short, Dispose is there for a reason - call it, or face nasty bugs
which can be a real pain to fix (partly because the behaviour will
change between debug and release).

--
Jon Skeet - <sk***@pobox.com>
http://www.pobox.com/~skeet
If replying to the group, please do not mail me too
Nov 16 '05 #8
Jon,
I didn't know that. Thanks for sharing!

Best regards,
Jeffrey Palermo
http://www.jeffreypalermo.com

Nov 16 '05 #9
Thanks everybody for your feedback. Pretty much what I get out of this is
that I should be calling Dispose if it's available and don't worry too much
about setting the variable to null. So I can pretty much follow either of
these patterns:

DataAdapter da = null;
try {
// Some logic here...
} catch (Exception ex) {
// Some exception handling logic here - only if I need an exception
handler at this level
} finally {
// Clean up...
if (da != null) {
da.Dispose();
}

--- or ---

DataAdapter da = null;
try {
using { da = new DataAdapter(...)
// Some logic here...
}
} catch (Exception ex) {
// Some exception handling logic here - only if I need an exception
handler at this level
}

--

Jeff Bramwell
Digerati Technologies, LLC
www.digeratitech.com

Manage Multiple Network Configurations with Select-a-Net
www.select-a-net.com
Nov 16 '05 #10
Yes, Jon. You're right. Thanks for sharing your idea. What I meant to most
objects that doesn't consume unmanaged resources, we needn't worry about
disposing the object, but GC will take care of it.

Kevin Yu
=======
"This posting is provided "AS IS" with no warranties, and confers no
rights."

Nov 16 '05 #11
Kevin Yu [MSFT] <v-****@online.microsoft.com> wrote:
Yes, Jon. You're right. Thanks for sharing your idea. What I meant to most
objects that doesn't consume unmanaged resources, we needn't worry about
disposing the object, but GC will take care of it.


Yes - but in those cases you *can't* dispose of the object because they
won't implement IDisposable :)

(The exceptions are things which inherit from MarshalByValueComponent,
Stream or whatever without really needing to dispose of anything. Even
so, it's often worth calling Dispose in those cases as there may well
be a finalizer - while many classes in that situation tell the GC to
suppress finalization, others may not.)

--
Jon Skeet - <sk***@pobox.com>
http://www.pobox.com/~skeet
If replying to the group, please do not mail me too
Nov 16 '05 #12
Jeff B. <js*@community.nospam> wrote:
Thanks everybody for your feedback. Pretty much what I get out of this is
that I should be calling Dispose if it's available and don't worry too much
about setting the variable to null. So I can pretty much follow either of
these patterns:

DataAdapter da = null;
try {
// Some logic here...
} catch (Exception ex) {
// Some exception handling logic here - only if I need an exception
handler at this level
} finally {
// Clean up...
if (da != null) {
da.Dispose();
}

--- or ---

DataAdapter da = null;
try {
using { da = new DataAdapter(...)
// Some logic here...
}
} catch (Exception ex) {
// Some exception handling logic here - only if I need an exception
handler at this level
}


I'd actually go for:

using (DataAdapter da = new DataAdapter(...))
{
try
{
...
}
catch
{
...
}
}

That way it keeps the scope of da tighter.

--
Jon Skeet - <sk***@pobox.com>
http://www.pobox.com/~skeet
If replying to the group, please do not mail me too
Nov 16 '05 #13

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

10
by: Henrik Dahl | last post by:
Hello! After I've finished using an instance of the SqlCommand class, should I then invoke Dispose() on the instance. I suppose so, as there is a Dispose method, but what does it actually...
0
by: Tal Sharfi | last post by:
Hi everyone I recently had the need for StringGrid object same as the one that Delphi has. An object that helps show lists of other objects in a simple grid. I searched the news groups and...
4
by: Joey | last post by:
Hi, I have come across codes like this if(dbConn != null) { dbConn.dispose(); } and sometimes like
0
by: Terry-OMAF | last post by:
I'm trying to create a web service in C# to populate a drop down in MS InfoPath with Active Directory users. How do I return what's found (if possble please provide code)? Not sure ift's the...
5
by: Stephanie_Stowe | last post by:
Hi. I am trying to get used to AS.NET. I have been doing ASP classic for years, and am now in a position to do ASP.NET. I am in the stumbling around until I get my bearings phase. I hope you will...
18
by: Sender | last post by:
Yesterday there was a very long thread on this query. (You can search on this by post by 'sender' with subject 'Simple Problem' post date Oct 7 time 1:43p) And in the end the following code was...
13
by: peter hansen | last post by:
in VB6 it was possible to load and unload forms - how do I do this in VB.NET :D I think I have been almost everywhere // Peter
6
by: Brian | last post by:
Hello, I am using a beginners book on VB .net and already stumped....when using this code (below) , it will tell me that MsgBox is not valid. This is a very simple program and I can't figure out...
156
by: Dennis | last post by:
Ok, I'm trying to dispose of every object that I create that has a dispose method based on advice from this newsgroup. However, I'm not sure how to dispose of the following object that was created...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
0
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.