473,320 Members | 2,020 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,320 software developers and data experts.

close() and dispose()

Is it a bad idea to do both once I'm done with an object?

Eric B.
Oct 9 '08 #1
18 4105
I always do close & dispose.

It might clear up the memory allocation. But if you're inside a
private method, it will probably get destroy once you leave that
method.
On Oct 9, 12:32*am, "Eric B." <bigb...@sesamestreet.comwrote:
Is it a bad idea to do both once I'm done with an object?

Eric B.
Oct 9 '08 #2
On Thu, 09 Oct 2008 00:32:09 -0700, Eric B. <bi*****@sesamestreet.com>
wrote:
Is it a bad idea to do both once I'm done with an object?
It's never a _bad_ idea to do both.

Many classes document that the two methods are equivalent, or that the
Close() always calls Dispose(), that sort of thing. And I suppose in
those cases, you can legitimately get away with doing only one or the
other (as appropriate based on the docs).

But personally, I tend to always do both. To me, the two are semantically
different, even if they often wind up doing the same thing in practice.

Pete
Oct 9 '08 #3
On Oct 9, 9:00*am, Slickuser <slick.us...@gmail.comwrote:
I always do * close & dispose.

It might clear up the memory allocation.
No it won't.
But if you're inside a
private method, it will probably get destroy once you leave that
method.
No it won't.

Close() and Dispose() don't release memory. They may occasionally
release references that they may have to other objects, but unless
they then explicitly call GC.Collect() - which would be a bad idea -
that's not going to release any memory.

Personally I just use a "using" block which will automatically call
Dispose(), and don't worry about Close(). If I ever come across a type
which implements IDisposable but which I need to explicitly Close() in
common situations, I'll complain to the author.

Jon
Oct 9 '08 #4
On Oct 9, 9:05*am, "Peter Duniho" <NpOeStPe...@nnowslpianmk.com>
wrote:

<snip>
But personally, I tend to always do both. *To me, the two are semantically *
different, even if they often wind up doing the same thing in practice.
Do you Close() in a finally block, or just at the end of the normal
execution?

I don't see the benefit of explicitly calling Close() if Dispose() is
going to do everything I want - which in my experience it does with
every disposable type I've been interested in. It's just more clutter
for no reason - I explicitly indicate that I want to scope-limit the
resource usage with a "using" statement; anything else is extraneous
IMO.

Jon
Oct 9 '08 #5
If you can reopen something then I would use Close(), but only if I intended
to reopen. If I intend to finish with the object completely I would ONLY
call Dispose. The reason is that if Dispose is implemented properly (and it
should be) then it will do everything Close() does plus possibly more.

x.Close();
x.Dispose();

You are wasting your life typing it :-)

--
Pete
====
http://mrpmorris.blogspot.com
http://www.capableobjects.com

Oct 9 '08 #6
If memory serves me correctly, some cases such as streams close calls
dispose, for most others dispose calls close. Call both is an exercise in
futility roughly equivalent to setting an int variable to 0 after using it -
well that's a stretch. Like Jon, I use the using statement and let the
framework figure out which call is prudent.

--
Regards,
Alvin Bruney

Want a free copy of VS 2008 w/ MSDN premium subscription?
Details at http://msmvps.com/blogs/alvin/Default.aspx

Auther Plug
OWC Blackbook now on download at www.lulu.com/owc

"Jon Skeet [C# MVP]" <sk***@pobox.comwrote in message
news:ef**********************************@n1g2000p rb.googlegroups.com...
On Oct 9, 9:05 am, "Peter Duniho" <NpOeStPe...@nnowslpianmk.com>
wrote:

<snip>
>But personally, I tend to always do both. To me, the two are semantically
different, even if they often wind up doing the same thing in practice.

Do you Close() in a finally block, or just at the end of the normal
execution?

I don't see the benefit of explicitly calling Close() if Dispose() is
going to do everything I want - which in my experience it does with
every disposable type I've been interested in. It's just more clutter
for no reason - I explicitly indicate that I want to scope-limit the
resource usage with a "using" statement; anything else is extraneous
IMO.

Jon
Oct 9 '08 #7
Alvin Bruney [ASP.NET MVP] wrote:
If memory serves me correctly, some cases such as streams close calls
dispose, for most others dispose calls close. Call both is an exercise
in futility roughly equivalent to setting an int variable to 0 after
using it - well that's a stretch. Like Jon, I use the using statement
and let the framework figure out which call is prudent.
For some classes, like a file stream, there is no difference between
calling Close and calling Dispose. You can't reopen the stream once it's
closed, you have to open a new stream. Those classes could call Dispose
from the Close method as you mention.

For some other classes, like a database connection, there is a
difference. If you close the connection, you can reopen it again, which
should use slightly less resources than creating a new one. Once you
have disposed the connection object, you can't use it any more.

--
Göran Andersson
_____
http://www.guffa.com
Oct 9 '08 #8
On Oct 9, 3:36*am, "Peter Morris" <mrpmorri...@SPAMgmail.comwrote:
If you can reopen something then I would use Close(), but only if I intended
to reopen. *If I intend to finish with the object completely I would ONLY
call Dispose. *The reason is that if Dispose is implemented properly (and it
should be) then it will do everything Close() does plus possibly more.
Ditto. That is exactly what I do as well.
Oct 9 '08 #9
On Oct 9, 3:24*am, "Jon Skeet [C# MVP]" <sk...@pobox.comwrote:
On Oct 9, 9:00*am, Slickuser <slick.us...@gmail.comwrote:
I always do * close & dispose.
It might clear up the memory allocation.

No it won't.
But if you're inside a
private method, it will probably get destroy once you leave that
method.

No it won't.

Close() and Dispose() don't release memory. They may occasionally
release references that they may have to other objects, but unless
they then explicitly call GC.Collect() - which would be a bad idea -
that's not going to release any memory.

Personally I just use a "using" block which will automatically call
Dispose(), and don't worry about Close(). If I ever come across a type
which implements IDisposable but which I need to explicitly Close() in
common situations, I'll complain to the author.

Jon
One clarification...both Close and Dispose often do release unmanaged
memory though.
Oct 9 '08 #10
On Oct 9, 2:25*pm, Göran Andersson <gu...@guffa.comwrote:
For some classes, like a file stream, there is no difference between
calling Close and calling Dispose. You can't reopen the stream once it's
closed, you have to open a new stream. Those classes could call Dispose
from the Close method as you mention.

For some other classes, like a database connection, there is a
difference. If you close the connection, you can reopen it again, which
should use slightly less resources than creating a new one. Once you
have disposed the connection object, you can't use it any more.
All of that is true - but I personally have never used that
functionality in any disposable class I've come across. Simple
database connection pooling has always been fine for me :)

If I *did* start relying on the difference between Close and Dispose
somewhere, I'd want to include a big comment explaining why, so that a
maintenance developer (possibly me!) didn't change it later and
inadvertently break something.

Jon
Oct 9 '08 #11
On Thu, 09 Oct 2008 01:26:32 -0700, Jon Skeet [C# MVP] <sk***@pobox.com>
wrote:
On Oct 9, 9:05Â*am, "Peter Duniho" <NpOeStPe...@nnowslpianmk.com>
wrote:

<snip>
>But personally, I tend to always do both. Â*To me, the two are
semantically Â*
different, even if they often wind up doing the same thing in practice.

Do you Close() in a finally block, or just at the end of the normal
execution?
I close inside the finally block.
I don't see the benefit of explicitly calling Close() if Dispose() is
going to do everything I want - which in my experience it does with
every disposable type I've been interested in.
Absent a mandate in the .NET specifications, it's not guaranteed
behavior. And it's worse to forget to close or dispose something that
needed to be than to do both when one would suffice. I find it annoying
to have to keep going back to the docs just to make sure I remembered the
behavior correctly for a specific class (heaven knows I mis-remember all
sorts of other things), so I just do both when both makes sense and leave
it at that.

To me, a close is a specific operation affecting specific state of the
object while a dispose is a clean-up activity.
It's just more clutter
for no reason - I explicitly indicate that I want to scope-limit the
resource usage with a "using" statement; anything else is extraneous
IMO.
I don't have an objection to that. I prefer my own approach, obviously,
but I don't agree that the extra call to Close() is "for no reason", and
thus don't come to the same conclusion about it as you do.

Pete
Oct 9 '08 #12
Peter Duniho <Np*********@nnowslpianmk.comwrote:
Do you Close() in a finally block, or just at the end of the normal
execution?

I close inside the finally block.
Which means life is as bad as Java, without a using statement :(
I don't see the benefit of explicitly calling Close() if Dispose() is
going to do everything I want - which in my experience it does with
every disposable type I've been interested in.

Absent a mandate in the .NET specifications, it's not guaranteed
behavior.
True in a general sense. Not true on a per-type basis, of course - and
I think any type which didn't act appropriately when being disposed
would be severely criticised, to be honest.
And it's worse to forget to close or dispose something that
needed to be than to do both when one would suffice. I find it annoying
to have to keep going back to the docs just to make sure I remembered the
behavior correctly for a specific class (heaven knows I mis-remember all
sorts of other things), so I just do both when both makes sense and leave
it at that.
I think I've checked out all the classes which I care about and come to
the view that there aren't any differences I'm worried about. I'd
rather have the more readable code.

<snip>

--
Jon Skeet - <sk***@pobox.com>
Web site: http://www.pobox.com/~skeet
Blog: http://www.msmvps.com/jon.skeet
C# in Depth: http://csharpindepth.com
Oct 9 '08 #13
>Once you
have disposed the connection object, you can't use it any more.

Dispose doesn't dispose of the connection at all. It flags it as closed and
returns it to the pool. If the timeout period expires, then it is disposed.
But I understand what you are saying.

--
Regards,
Alvin Bruney

Want a free copy of VS 2008 w/ MSDN premium subscription?
Details at http://msmvps.com/blogs/alvin/Default.aspx

Auther Plug
OWC Blackbook now on download at www.lulu.com/owc

"Göran Andersson" <gu***@guffa.comwrote in message
news:#G*************@TK2MSFTNGP03.phx.gbl...
Alvin Bruney [ASP.NET MVP] wrote:
>If memory serves me correctly, some cases such as streams close calls
dispose, for most others dispose calls close. Call both is an exercise in
futility roughly equivalent to setting an int variable to 0 after using
it - well that's a stretch. Like Jon, I use the using statement and let
the framework figure out which call is prudent.

For some classes, like a file stream, there is no difference between
calling Close and calling Dispose. You can't reopen the stream once it's
closed, you have to open a new stream. Those classes could call Dispose
from the Close method as you mention.

For some other classes, like a database connection, there is a difference.
If you close the connection, you can reopen it again, which should use
slightly less resources than creating a new one. Once you have disposed
the connection object, you can't use it any more.

--
Göran Andersson
_____
http://www.guffa.com
Oct 10 '08 #14
I don't agree at all. How would you write the guidelines for this so that
junior developers would follow this without getting confused? The
recommendation from Microsoft is to use the using construct if it is
available. That takes care of most of the cases. Particular cases like
passing back opened readers obviously won't fit the recommendation and are
to be treated as special cases.

In any case, you are calling close in a finally block are you not? You are
calling dispose in a finally block, are you not? Why not let the framework
figure out the most appropriate call - hence the using statement which
unrolls to exactly what you are hand coding? For instance, calling dispose
on a sql adapter object is perfectly useless since it is purely managed
resource.

--
Regards,
Alvin Bruney

Want a free copy of VS 2008 w/ MSDN premium subscription?
Details at http://msmvps.com/blogs/alvin/Default.aspx

Auther Plug
OWC Blackbook now on download at www.lulu.com/owc

"Brian Gideon" <br*********@yahoo.comwrote in message
news:96**********************************@r38g2000 prr.googlegroups.com...
On Oct 9, 3:36 am, "Peter Morris" <mrpmorri...@SPAMgmail.comwrote:
>If you can reopen something then I would use Close(), but only if I
intended
to reopen. If I intend to finish with the object completely I would ONLY
call Dispose. The reason is that if Dispose is implemented properly (and
it
should be) then it will do everything Close() does plus possibly more.

Ditto. That is exactly what I do as well.
Oct 10 '08 #15
On Thu, 09 Oct 2008 12:13:41 -0700, Jon Skeet [C# MVP] <sk***@pobox.com>
wrote:
Peter Duniho <Np*********@nnowslpianmk.comwrote:
Do you Close() in a finally block, or just at the end of the normal
execution?

I close inside the finally block.

Which means life is as bad as Java, without a using statement :(
As bad as? Oh, come on. I think you're exaggerating, quite a lot.
Adding the extra call to Close() doesn't do anything like make C# "as bad
as" Java (not that I think Java is that bad anyway, but certainly I find
..NET/C# much nicer).

In any case, the kind of code I work on this doesn't come up much. Maybe
if I were dealing with these classes a lot I'd have a different opinion.
But I don't, and I don't. :p

Pete
Oct 10 '08 #16
Peter Duniho <Np*********@nnowslpianmk.comwrote:
I close inside the finally block.
Which means life is as bad as Java, without a using statement :(

As bad as? Oh, come on. I think you're exaggerating, quite a lot.
Adding the extra call to Close() doesn't do anything like make C# "as bad
as" Java (not that I think Java is that bad anyway, but certainly I find
.NET/C# much nicer).
I meant in terms of this particular aspect - I've always found it
amazing how much difference the using statement makes to readability,
virtually eliminating try/finally blocks. As those are much more common
than try/catch blocks (particularly in .NET where you don't need to
convert exceptions all the time due to checked exception rules) I
suspect my density of explicit try blocks in C# is way, way lower than
in Java.

I'd need hard evidence that relying on Dispose was actually costing me
something before I'd effectively give us the using statement :)
In any case, the kind of code I work on this doesn't come up much. Maybe
if I were dealing with these classes a lot I'd have a different opinion.
But I don't, and I don't. :p
:)

--
Jon Skeet - <sk***@pobox.com>
Web site: http://www.pobox.com/~skeet
Blog: http://www.msmvps.com/jon.skeet
C# in Depth: http://csharpindepth.com
Oct 10 '08 #17
Brian Gideon wrote:
One clarification...both Close and Dispose often do release unmanaged
memory though.
Dispose always does (if it's implemented correctly of couse).

Close may or may not do that, depending on what it's supposed to do. The
Close method for a database connection for example allows the connection
to be reopened later, while the Dispose method frees the resources that
allows that.

--
Göran Andersson
_____
http://www.guffa.com
Oct 10 '08 #18
The point is that some objects implement a Close() method just because it
makes more sense logically than Dispose. For example FileStream.Close()
means more to me than FileStream.Dispose(). If an object has a Close()
method and doesn't call it from Dispose I would consider that to be poor
programming, or at the very least confusing!

I can see however that in a pooled collection of SomeThing you might want
Dispose to return it to the pool and Close to actually kill it off, but I
would *still* consider this confusing. I'd be more inclined to implement
Activate/Deactivate or IsActive instead of Open/Close. My original
statement was that *if* the object implements Close in such a way that the
object may be re opened then I would only call Close if I intended to later
reopen it. Otherwise I would always dispose of it (actually via the using
statement).

--
Pete
====
http://mrpmorris.blogspot.com
http://www.capableobjects.com

Oct 10 '08 #19

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

Similar topics

7
by: Willem van Rumpt | last post by:
Hi all, coming from an unmanaged programming background, I took my time to sort out the IDisposable and finalizer patterns. Just when I thought I had it all conceptually neatly arranged, the...
10
by: Jim H | last post by:
I sometimes get the following error from my Form's Dispose Method when the application is closing: ------------------------------------------------- An unhandled exception of type...
6
by: Ashish | last post by:
It might be basics for many but I never gave attention on this before. Steps: Add 2 forms (Form1/Form2) in application. Create a object in Form1 for Form2. Form2 f2 = new Form2(); //line...
1
by: Bob | last post by:
Is this a good way to close DB Connection in ASP.NET? I've been trying to come up a way to close DB connection automatically (or sort of) in my ASP.NET application without having to write the...
8
by: Pierson C | last post by:
I am developing on a website that is utilizing SQL Server 2000. Shortly after deploying the site, we began having timeout issues due to the max connections. 1st instinct was to diligently tidy...
6
by: Simon Harris | last post by:
Hi All, Do I need to use both Conn.Close() & Conn.Dispose() when I have finished with an SQL connection? -- I am using the free version of SPAMfighter for private users. It has removed...
19
by: Nathan | last post by:
I know this has been asked previously, but I've run into a situation where I need to know the difference between close and dispose, and I can't get the information I need from msdn help or previous...
35
by: Eric Sabine | last post by:
In my Finally block, I was using cn.close (where cn is an ADO.NET connection object, SQLConnection to be exact) and then I came across the following in some microsoft code. If Not cn Is Nothing...
8
by: Paul W | last post by:
Hi - in an asp.net application, how should I close out a sqlclient.connection? What combination and order of Conn.close conn.dispose conn=nothing Should I use? Specifically, is the...
3
by: Joris De Groote | last post by:
Hi, I use Adobe Acrobat to read tekst from PDF files. After that the file has been read, I move the file in a folder (using the date I got from the text I got from Acrobat). Now here is my...
0
by: DolphinDB | last post by:
The formulas of 101 quantitative trading alphas used by WorldQuant were presented in the paper 101 Formulaic Alphas. However, some formulas are complex, leading to challenges in calculation. Take...
0
by: DolphinDB | last post by:
Tired of spending countless mintues downsampling your data? Look no further! In this article, you’ll learn how to efficiently downsample 6.48 billion high-frequency records to 61 million...
0
by: ryjfgjl | last post by:
ExcelToDatabase: batch import excel into database automatically...
0
by: jfyes | last post by:
As a hardware engineer, after seeing that CEIWEI recently released a new tool for Modbus RTU Over TCP/UDP filtering and monitoring, I actively went to its official website to take a look. It turned...
0
by: ArrayDB | last post by:
The error message I've encountered is; ERROR:root:Error generating model response: exception: access violation writing 0x0000000000005140, which seems to be indicative of an access violation...
1
by: PapaRatzi | last post by:
Hello, I am teaching myself MS Access forms design and Visual Basic. I've created a table to capture a list of Top 30 singles and forms to capture new entries. The final step is a form (unbound)...
0
by: CloudSolutions | last post by:
Introduction: For many beginners and individual users, requiring a credit card and email registration may pose a barrier when starting to use cloud servers. However, some cloud server providers now...
0
by: Defcon1945 | last post by:
I'm trying to learn Python using Pycharm but import shutil doesn't work
0
by: Shællîpôpï 09 | last post by:
If u are using a keypad phone, how do u turn on JavaScript, to access features like WhatsApp, Facebook, Instagram....

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.