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
16 4263
"Scott Allen" <bitmask@[nospam].fred.net> wrote in message
news:9l******** *************** *********@4ax.c om... 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.
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/
"Scott Allen" <bitmask@[nospam].fred.net> wrote in message
news:en******** *************** *********@4ax.c om... 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?
"Daniel O'Connell [C# MVP]" <onyxkirx@--NOSPAM--comcast.net> wrote in
message news:OW******** ******@TK2MSFTN GP09.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"(para phrased 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.
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 SqlConnectio n, 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?
"Scott Allen" <bitmask@[nospam].fred.net> wrote in message
news:u4******** *************** *********@4ax.c om... 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!
"John Vottero" <Jo**@mvpsi.com > wrote in message
news:e5******** ******@TK2MSFTN GP12.phx.gbl... "Scott Allen" <bitmask@[nospam].fred.net> wrote in message news:u4******** *************** *********@4ax.c om... 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. This thread has been closed and replies have been disabled. Please start a new discussion. Similar topics |
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 Dispose method of
IDbConnection. This Dispose method is called from a destructor. In the
dispose method, i also call GC.SuppressFinalize(this) so as to avoid
finalizer. All this was OK untill i came across one article that says - not
to call...
|
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 release refrence from memory ?
E. If it release object from memory then what GC does ?
2. Which class can have dispose method ?
class which is member of IDispose Inteface
3. Where we should use abstract / Interface ?
|
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 happen if I just
create my own Dispose (or any other name) mehtod, without implementing
the IDisposable interface. In all the examples, which I found, this
Dispose method called from my user code (not by GC). What do I miss?
Thanks.
|
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.
CType(connection, IDisposable).Dispose()
Is there any reason that you couldn't just do:
connection.Dispose() ?
What is the difference?
|
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 just make a Sub Dispose() and
the CLR will know that this is the Dispose method to call when the object
falls out of scope?
Thanks.
| |
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
End Class
now where would I properly dispose of this? In the finalize method? I am
loading the data for the table in a subroutine that is executed at form
load, of course all the commands tied to it are wrapped in using blocks, but
|
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 ControlClosed event.
I can put my code into UserControl.Desgner.cs Dispose method, but that seems
to be a bad practive.
What do I do?
|
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, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look !
Part I. Meaning of...
|
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 effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it.
First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
|
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...
|
by: tracyyun |
last post by:
Dear forum friends,
With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
| |
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...
|
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();...
|
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...
|
by: 6302768590 |
last post by:
Hai team
i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
|
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...
| |