473,813 Members | 4,172 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

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 4417
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******** ******@TK2MSFTN GP14.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.co m>
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.co m>
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.mic rosoft.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.co m>
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

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

Similar topics

10
18560
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 release? I would basically prefer to skip invoking Dispose() as this will free me from determining when the usage actually has finished.
0
7572
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 found none, so, I wrote one and decided to share it with you. It's a very simple one with few functions. I derived a DataGrid and added to it a DataTable to hold the data. The object itself is handling the synchronization between them, because...
4
2006
by: Joey | last post by:
Hi, I have come across codes like this if(dbConn != null) { dbConn.dispose(); } and sometimes like
0
1292
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 right group to ask my second question, if not I'll try the InfoPath group but I'll throw it in anyways. From the InfoPath side, I've seen a couple different ways to receive the data such as: http://support.microsoft.com/?id=826994...
5
2631
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 bear with me. I am going through the QuickStart. After reading a little, I am trying to implement a simple page on a simple project I have made up. I have a page called default.aspx. I want it to load a list of user names from a SQL database...
18
1517
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 decided to open a new form: ---Code in the click event of a button: button1 if frm is nothing then frm = new form2() frm.show
13
1293
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
1442
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 what the problem is: Public Class Form1 Inherits System.Windows.Forms.Form
156
5916
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 inside a method call. dim myvar as new object1 object1.dosomethingmethod(new object2) Note that object 2 has a dispose method but how do I dispose of it unless I do the following:
0
10665
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
1
10420
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 Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
9221
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
7681
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6897
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5568
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
5704
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
3881
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
3029
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.