473,382 Members | 1,363 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,382 software developers and data experts.

Always dispose of an object that implements the IDisposible interface?

If an object implements the IDisposable interface (regardless if its a
framework object or a user object), should I always dispose of that
object out of principle?
Nov 16 '05 #1
16 4220
"Daniel Mori" <sb******@hotmail.com> wrote:
If an object implements the IDisposable interface
(regardless if its a framework object or a user
object), should I always dispose of that object
out of principle?


If a class implements IDisposable, it almost certainly has resources
that need freeing up - so yes, you should. A 'using' block will ensure
that you don't forget to do this:

using (DisposableThing x = new DisposableThing())
{
// ... do something with x ...
}

P.
Nov 16 '05 #2
"Paul E Collins" <fi******************@CL4.org> wrote in message
news:cl**********@hercules.btinternet.com...
If a class implements IDisposable, it almost certainly has resources
that need freeing up - so yes, you should. A 'using' block will ensure
that you don't forget to do this:


I don't know if this is always true. For example the sqlConnection can just
be closed.

Michael Culley
Nov 16 '05 #3
"Michael Culley" <mc*****@NOSPAMoptushome.com.au> wrote in message
news:u3**************@TK2MSFTNGP11.phx.gbl...
"Paul E Collins" <fi******************@CL4.org> wrote in message
news:cl**********@hercules.btinternet.com...
If a class implements IDisposable, it almost certainly has resources
that need freeing up - so yes, you should. A 'using' block will ensure
that you don't forget to do this:


I don't know if this is always true. For example the sqlConnection can
just
be closed.


Today, the only thing that SqlConnection's Dispose method does is make sure
the connection is closed. Tomorrow, it could do something else. If you
want to be a good citizen, call Dispose and pretend that you don't know what
it does.
Nov 16 '05 #4

"John Vottero" <Jo**@mvpsi.com> wrote in message
news:eW**************@tk2msftngp13.phx.gbl...
"Michael Culley" <mc*****@NOSPAMoptushome.com.au> wrote in message
news:u3**************@TK2MSFTNGP11.phx.gbl...
"Paul E Collins" <fi******************@CL4.org> wrote in message
news:cl**********@hercules.btinternet.com...
If a class implements IDisposable, it almost certainly has resources
that need freeing up - so yes, you should. A 'using' block will ensure
that you don't forget to do this:


I don't know if this is always true. For example the sqlConnection can
just
be closed.


Today, the only thing that SqlConnection's Dispose method does is make
sure the connection is closed. Tomorrow, it could do something else. If
you want to be a good citizen, call Dispose and pretend that you don't
know what it does.


When dealing with objects that use the Close pattern, Close and Dispose
*should* be, at least, functionally similar, any that are not are broken(I
think SqlConnection itself is one which differs its implementations, leading
to some annoyance). IDisposable is provided to allow using and other such
statements\frameworks to formazlie access to the disposal method, but in
itself offers no more guarentees than Close does. There is no real need to
call dispose on objects that provide a Close method as a matter of common
practice, if not standard per se. Remember, there is no guarentee that
Dispose will actually do any good or will be the right method to use. If a
Close method is provided, it likely is well thought out and should be used
when not using the using statement, otherwise the class designer wouldn't
have included it(in most cases Dispose will be explicitly implemented when
Close is appropriate, and a cast call is almost certainly the wrong thing to
do).

There is a reason Close exists period, and its not just to look pretty.
Using using is usually the better pattern, but that is a matter of design
and appropriatness, not requirements.
Nov 16 '05 #5
"Daniel O'Connell [C# MVP]" <onyxkirx@--NOSPAM--comcast.net> wrote in
message news:uL**************@TK2MSFTNGP11.phx.gbl...
When dealing with objects that use the Close pattern, Close and Dispose
*should* be, at least, functionally similar, any that are not are broken(I
think SqlConnection itself is one which differs its implementations, leading to some annoyance).


I would expect that close might raise exceptions under some situations where
dispose did not. This was the case with vb6 where closing a recordset would
raise an error if an update was no committed but setting it to nothing would
ignore the error.
Nov 16 '05 #6

"Daniel Mori" <sb******@hotmail.com> wrote in message
news:d2************************@posting.google.com ...
If an object implements the IDisposable interface (regardless if its a
framework object or a user object), should I always dispose of that
object out of principle?


You should always dispose the object if the object implements IDisposable
*and* you own the object (in other words, you know that no-one else is going
to use the object after you are done with it).

Regards,
Sami
Nov 16 '05 #7
"Daniel O'Connell [C# MVP]" <onyxkirx@--NOSPAM--comcast.net> wrote in
message news:uL****************@TK2MSFTNGP11.phx.gbl...

"John Vottero" <Jo**@mvpsi.com> wrote in message
news:eW**************@tk2msftngp13.phx.gbl...
"Michael Culley" <mc*****@NOSPAMoptushome.com.au> wrote in message
news:u3**************@TK2MSFTNGP11.phx.gbl...
"Paul E Collins" <fi******************@CL4.org> wrote in message
news:cl**********@hercules.btinternet.com...
If a class implements IDisposable, it almost certainly has resources
that need freeing up - so yes, you should. A 'using' block will ensure
that you don't forget to do this:

I don't know if this is always true. For example the sqlConnection can
just
be closed.

Today, the only thing that SqlConnection's Dispose method does is make
sure the connection is closed. Tomorrow, it could do something else. If
you want to be a good citizen, call Dispose and pretend that you don't
know what it does.


When dealing with objects that use the Close pattern, Close and Dispose
*should* be, at least, functionally similar, any that are not are broken(I


I would expect Close to be a subset of Dispose.
think SqlConnection itself is one which differs its implementations,
leading to some annoyance). IDisposable is provided to allow using and
other such statements\frameworks to formazlie access to the disposal
method, but in itself offers no more guarentees than Close does. There is
no real need to call dispose on objects that provide a Close method as a
matter of common practice, if not standard per se. Remember, there is no
guarentee that Dispose will actually do any good or will be the right
method to use. If a Close method is provided, it likely is well thought
out and should be used when not using the using statement, otherwise the
class designer wouldn't have included it(in most cases Dispose will be
explicitly implemented when Close is appropriate, and a cast call is
almost certainly the wrong thing to do).

There is a reason Close exists period, and its not just to look pretty.
Using using is usually the better pattern, but that is a matter of design
and appropriatness, not requirements.


It's just wrong to believe that if an object has a Close method, that method
does the same thing as Dispose. It's also wrong to believe that there's no
need to call an object's Dispose method because you know what Dispose does.

Nov 16 '05 #8
On Mon, 25 Oct 2004 16:17:52 -0400, "John Vottero" <Jo**@mvpsi.com>
wrote:

It's just wrong to believe that if an object has a Close method, that method
does the same thing as Dispose. It's also wrong to believe that there's no
need to call an object's Dispose method because you know what Dispose does.


Unfortunately, this is exactly what the parts of the framework want
people to think (we don't want people to think they have to Dispose a
FileStream, so let's implement IDisposable explicitly and provide a
Close method for everyone to call). The end result has been massive
amounts of confusion.

--
Scott
http://www.OdeToCode.com/blogs/scott/
Nov 16 '05 #9
>>>
Today, the only thing that SqlConnection's Dispose method does is make
sure the connection is closed. Tomorrow, it could do something else.
If you want to be a good citizen, call Dispose and pretend that you
don't know what it does.


When dealing with objects that use the Close pattern, Close and Dispose
*should* be, at least, functionally similar, any that are not are
broken(I


I would expect Close to be a subset of Dispose.


Why? There is *no* convention that says so. Infact DIspose is there to
"pefrom application-defined tasks associated with freeing, releasing, or
resetting unmanaged resources"(paraphrased from MSDN), that sounds more like
a subset of Close to me.

For all you know dispose does not close the object or does anything else
similar to Close. The only saving grace Dispose has is that, as common
practice, Dispose and Close are similar or identical. In any other case you
end up with broken API's and a useless IDisposable contract.

If Close is anything but an equal to Dispose you end up with scenarios where
users are forced to know what each means and to apply each particular method
in the circumstance nessecery. That ends you with two seperate states
(Closed and Disposed), increasing possible exceptions and the complete
complexity of the class itself. You end up with circumstances where objects
are only cleaned up due to one path while the other causes surprises. You
end up with scenarios where you cannot use using. In effect, if Close and
Dispose aren't considered equal, you risk Dispose having Reset or Free and
Reload sematics instead of Close semantics.

There is a reason Close exists period, and its not just to look pretty.
Using using is usually the better pattern, but that is a matter of design
and appropriatness, not requirements.


It's just wrong to believe that if an object has a Close method, that
method does the same thing as Dispose. It's also wrong to believe that
there's no need to call an object's Dispose method because you know what
Dispose does.


And by that logic it is equally wrong to assume that because an object has a
Dispose method that you can call it instead of Close. You cannot rely on
Dispose anymore than Close, guess its best to call both every time, eh? For
that matter, you can't even safely call Dispose if you don't know what it
does because that may *reset* the content without flushing buffers or do
things which makes close illogical or surprising(like recycling
connections). If you cannot know these things, you cannot expect Dispose to
correctly close the object. If you cannot expect Dispose to close the object
you cannot expect Dispose to be a safe pattern.

Would it surprise you to know that there are many people who believe
IDisposable was a pattern that should never have been let loose? I don't
happen to agree to an extreme extent, but I do believe its one that an end
user should never be forced to directly call into and that the literal
definition is far too narrow to make the pattern really useful. It is only
useful as a pattern to formalize Close semantics for use by compilers and
frameworks; anything more stretches the usefulness of the pattern. Sadly,
the existing specified contract does not even fulfill that, even though that
is how IDisposable is usually used.
Nov 16 '05 #10

"Scott Allen" <bitmask@[nospam].fred.net> wrote in message
news:9l********************************@4ax.com...
On Mon, 25 Oct 2004 16:17:52 -0400, "John Vottero" <Jo**@mvpsi.com>
wrote:

It's just wrong to believe that if an object has a Close method, that
method
does the same thing as Dispose. It's also wrong to believe that there's
no
need to call an object's Dispose method because you know what Dispose
does.


Unfortunately, this is exactly what the parts of the framework want
people to think (we don't want people to think they have to Dispose a
FileStream, so let's implement IDisposable explicitly and provide a
Close method for everyone to call). The end result has been massive
amounts of confusion.


And yet, MemoryStream has no reason to be IDisposable under the contract of
IDisposable. It simply does not do what it should. IDisposable is nearly
broken and virtually no one implements it within the confines of the actual
interface meaning. IDisposable should be explicitly implemented in streams
and should never be called directly. It should not be used to close an
object and for MemoryStream, by all rights, it should be a nop. It is not
however, and as I've argued before, the only thing that makes IDisposable
valid is that it has been inextricably tied to Close semantics by the
framework and common practice. Any other usage of IDisposable is bound to
cause greater confusion that a Close method ever will.

Beyond that, I've yet to see anything near "massive amounts of confusion"
over Close. I've seen many over issues with IDisposable, but almost all of
those have nothing to do with a matching Close method. It is a minor issue
in a system where IDisposable is rarely actually implemented within its own
rules anyway. Perhaps the confusion really is because of IDisposable and not
Close methods?

And perhaps people saying "always use dispose and forget everything else" is
contributing more to the problems than it is anything else.
Nov 16 '05 #11
On Mon, 25 Oct 2004 21:11:33 -0500, "Daniel O'Connell [C# MVP]"
<onyxkirx@--NOSPAM--comcast.net> wrote:

Beyond that, I've yet to see anything near "massive amounts of confusion"
over Close. I've seen many over issues with IDisposable, but almost all of
those have nothing to do with a matching Close method. It is a minor issue
in a system where IDisposable is rarely actually implemented within its own
rules anyway. Perhaps the confusion really is because of IDisposable and not
Close methods?


Hi Daniel:

Yes, I think the epicenter of the confusion is centered directly on
top of the IDisposable interface, and the closer one sits to the
surface of the interface the greater the tremors are. Classes like
SqlConnection, having both Close and Dispose methods, have been
hotbeds of endless debate in newsgroups, mailing lists, and user group
meetings.

--
Scott
http://www.OdeToCode.com/blogs/scott/
Nov 16 '05 #12
"Scott Allen" <bitmask@[nospam].fred.net> wrote in message
news:en********************************@4ax.com...
On Mon, 25 Oct 2004 21:11:33 -0500, "Daniel O'Connell [C# MVP]"
<onyxkirx@--NOSPAM--comcast.net> wrote:

Beyond that, I've yet to see anything near "massive amounts of confusion"
over Close. I've seen many over issues with IDisposable, but almost all of
those have nothing to do with a matching Close method. It is a minor issue
in a system where IDisposable is rarely actually implemented within its
own
rules anyway. Perhaps the confusion really is because of IDisposable and
not
Close methods?


Hi Daniel:

Yes, I think the epicenter of the confusion is centered directly on
top of the IDisposable interface, and the closer one sits to the
surface of the interface the greater the tremors are. Classes like
SqlConnection, having both Close and Dispose methods, have been
hotbeds of endless debate in newsgroups, mailing lists, and user group
meetings.


I don't understand the confusion or the debate. When you want to close a
SqlConnection, call close. When you're done with an SqlConnection, call
Dispose. The call sequence is:

new
Open
...
Close
Open
...
Close
Open
...
Close
Open
...
Close
Dispose

Is it confusing because Dispose makes sure you called that last Close? (at
least, for SqlConnection) Would it be better if Dispose threw an exception
if the connection wasn't closed?
Nov 16 '05 #13
"Daniel O'Connell [C# MVP]" <onyxkirx@--NOSPAM--comcast.net> wrote in
message news:OW**************@TK2MSFTNGP09.phx.gbl...

Today, the only thing that SqlConnection's Dispose method does is make
sure the connection is closed. Tomorrow, it could do something else.
If you want to be a good citizen, call Dispose and pretend that you
don't know what it does.
When dealing with objects that use the Close pattern, Close and Dispose
*should* be, at least, functionally similar, any that are not are
broken(I
I would expect Close to be a subset of Dispose.


Why? There is *no* convention that says so. Infact DIspose is there to
"pefrom application-defined tasks associated with freeing, releasing, or
resetting unmanaged resources"(paraphrased from MSDN), that sounds more
like a subset of Close to me.


I realize that but there's also *no* convention that says that Close is in
any way related to Dispose.

For all you know dispose does not close the object or does anything else
similar to Close. The only saving grace Dispose has is that, as common
practice, Dispose and Close are similar or identical. In any other case
you end up with broken API's and a useless IDisposable contract.
Exactly! When I want to close an object, I call Close. When I'm done with
it, I call Dispose. Don't assume that the two are related.

If Close is anything but an equal to Dispose you end up with scenarios
where users are forced to know what each means and to apply each
particular method in the circumstance nessecery.
Is it unreasonable to ask users to know what methods do before they start
calling them?
That ends you with two seperate states (Closed and Disposed), increasing
possible exceptions and the complete complexity of the class itself.
But, there *are* two seperate states!
You end up with circumstances where objects are only cleaned up due to one
path while the other causes surprises. You end up with scenarios where you
cannot use using. In effect, if Close and Dispose aren't considered equal,
you risk Dispose having Reset or Free and Reload sematics instead of Close
semantics.
I do think of Dispose as free. If an object implements IDisposable, call
Dispose when you're done with it or you might leak "things". I see no
relationship to Close.

There is a reason Close exists period, and its not just to look pretty.
Using using is usually the better pattern, but that is a matter of
design and appropriatness, not requirements.
It's just wrong to believe that if an object has a Close method, that
method does the same thing as Dispose. It's also wrong to believe that
there's no need to call an object's Dispose method because you know what
Dispose does.


And by that logic it is equally wrong to assume that because an object has
a Dispose method that you can call it instead of Close. You cannot rely on


I never said that. When you want to close an object, call Close. When
you're done with it, call Dispose.
Dispose anymore than Close, guess its best to call both every time, eh?
For
Yes.
that matter, you can't even safely call Dispose if you don't know what it
does because that may *reset* the content without flushing buffers or do
things which makes close illogical or surprising(like recycling
connections). If you cannot know these things, you cannot expect Dispose
to correctly close the object. If you cannot expect Dispose to close the
object you cannot expect Dispose to be a safe pattern.
I *don't* expect Dispose to correctly close an object. Nor do I expect free
to close an object in a C++ program.

Would it surprise you to know that there are many people who believe
IDisposable was a pattern that should never have been let loose? I don't
happen to agree to an extreme extent, but I do believe its one that an end
user should never be forced to directly call into and that the literal
definition is far too narrow to make the pattern really useful. It is only
useful as a pattern to formalize Close semantics for use by compilers and
frameworks; anything more stretches the usefulness of the pattern. Sadly,
the existing specified contract does not even fulfill that, even though
that is how IDisposable is usually used.

Nov 16 '05 #14
Hi John:

The debate arises because in many cases the class designers have
offered the Close method as an alias for the Dispose method, thus
giving Close the same semantics as Dispose.

On aliasing the Dispose name...
http://blogs.msdn.com/brada/archive/.../06/50127.aspx

If you check around Angel Saenz-Badillos ADO.NET blog, you'll see the
terms Close and Dispose are used interchangably (often reffered to as
Close/Dispose).
http://blogs.msdn.com/angelsb/

Looking in the ASP.NET and ADO.NET newsgroups and forms over the years
I've seen people divide into the following camps:

The first camp says just invoke Dispose, or wrap the connection inside
of a using scope.

The second camp says just invoke the Close method.

The third camp insists on calling Close and Dispose.

The fourth camp says call Close, then Dispose, then set the object
reference to null or Nothing to make sure it's really, really, really,
dead.

At a presentation I did a couple weeks ago there was also a gentleman
who insisted you had to call Close twice - once inside a try block and
once inside a finally block.

As for your questions at the end: I personally would not want an
exception thrown if the connection was still open when I call Dispose.
I want Dispose to work in conjunction with the using statement and
just take care of all the work needed to tidy up after an object.

--
Scott
http://www.OdeToCode.com/

On Tue, 26 Oct 2004 11:53:14 -0400, "John Vottero" <Jo**@mvpsi.com>
wrote:

I don't understand the confusion or the debate. When you want to close a
SqlConnection, call close. When you're done with an SqlConnection, call
Dispose. The call sequence is:

new
Open
...
Close
Open
...
Close
Open
...
Close
Open
...
Close
Dispose

Is it confusing because Dispose makes sure you called that last Close? (at
least, for SqlConnection) Would it be better if Dispose threw an exception
if the connection wasn't closed?


Nov 16 '05 #15

"Scott Allen" <bitmask@[nospam].fred.net> wrote in message
news:u4********************************@4ax.com...
Hi John:

The debate arises because in many cases the class designers have
offered the Close method as an alias for the Dispose method, thus
giving Close the same semantics as Dispose.

On aliasing the Dispose name...
http://blogs.msdn.com/brada/archive/.../06/50127.aspx

Stream does add confusion because it hides Dispose.
If you check around Angel Saenz-Badillos ADO.NET blog, you'll see the
terms Close and Dispose are used interchangably (often reffered to as
Close/Dispose).
http://blogs.msdn.com/angelsb/

Looking in the ASP.NET and ADO.NET newsgroups and forms over the years
I've seen people divide into the following camps:

The first camp says just invoke Dispose, or wrap the connection inside
of a using scope.

The second camp says just invoke the Close method.

The third camp insists on calling Close and Dispose.

The fourth camp says call Close, then Dispose, then set the object
reference to null or Nothing to make sure it's really, really, really,
dead.


Count me in this camp!

Nov 16 '05 #16

"John Vottero" <Jo**@mvpsi.com> wrote in message
news:e5**************@TK2MSFTNGP12.phx.gbl...

"Scott Allen" <bitmask@[nospam].fred.net> wrote in message
news:u4********************************@4ax.com...
Hi John:

The debate arises because in many cases the class designers have
offered the Close method as an alias for the Dispose method, thus
giving Close the same semantics as Dispose.

On aliasing the Dispose name...
http://blogs.msdn.com/brada/archive/.../06/50127.aspx


Stream does add confusion because it hides Dispose.
If you check around Angel Saenz-Badillos ADO.NET blog, you'll see the
terms Close and Dispose are used interchangably (often reffered to as
Close/Dispose).
http://blogs.msdn.com/angelsb/

Looking in the ASP.NET and ADO.NET newsgroups and forms over the years
I've seen people divide into the following camps:

The first camp says just invoke Dispose, or wrap the connection inside
of a using scope.

The second camp says just invoke the Close method.

The third camp insists on calling Close and Dispose.

The fourth camp says call Close, then Dispose, then set the object
reference to null or Nothing to make sure it's really, really, really,
dead.


Count me in this camp!


....and then there's the "Hey! Let's check it out!" camp. Meaning use Ildasm
and the debugger to see what actually happens when using an
instance/combination of using/Close/Dispose is called. We might not want to
do this everytime we DESIGN something, but certainly as we get ready for its
release.
Nov 16 '05 #17

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

Similar topics

3
by: faktujaa | last post by:
Hi All, A small confusion. I have defined a connection class that has System.Data.IDbConnection as a member variable and implements IDisposable interface. I have implemented Dispose method to call...
4
by: RiteshDotNet | last post by:
..net Frame work 1. Dispose Method what it does ? A. who its call / when it calls ? B. Is it fire automatically ? c. When dispose method is call what it does ? D. Release a Object from memory or...
3
by: Maxim | last post by:
Hi! According to documenation, if we need to release some umanaged resources manually, we need to implement IDisposable interface with single Dispose method. I am just wondering, what will...
16
by: Jeremy | last post by:
I was looking through some sample code that Microsoft provided for data access and I noticed that when they call the Dispose() method on the Connection object they cast it to IDisposable first. ...
7
by: Scott M. | last post by:
In a typical class, do I need to indicate that it implements the IDisposable interface and then create a Dispose method that implements the Dispose required by the IDisposable interface or can I...
44
by: Smokey Grindle | last post by:
I have a list box on my form, but I need to databind it to a data table that is a private member of the form's class... so I basically have Public Class MyForm priate m_MyTable as new datatable...
6
by: =?Utf-8?B?VmljdG9y?= | last post by:
Hi, I have a UserControl (C# WinFroms application) that requires some cleaning code to run when a form with control is closed. Where I can put that code? There is no ControlClosing or...
1
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
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 3 Apr 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 former...
0
by: taylorcarr | last post by:
A Canon printer is a smart device known for being advanced, efficient, and reliable. It is designed for home, office, and hybrid workspace use and can also be used for a variety of purposes. However,...
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: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
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: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?

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.