to dispose or not ?

  • Thread starter Thread starter Michel Posseth [MCP]
  • Start date Start date
M

Michel Posseth [MCP]

After a time of abscense reading this newsgroup i read again a lot of
Dispose bashing
I can only say "Again ! " i thought we had discussed this several times

Some facts do not change over time , and if you really think calling dispose
isn`t necesary at all i invite you to write some AD code you will then find
that if you do not dispose the smallest object
your program will consume more and more resources untill it hits your
computers limit and blows up with a out of memory exception .

I also read about parrotting blah blah about using Dispose , however fact
is that calling Dispose is described in the documentation as a must ( page
202 of the official core reference guide of VB )

So in short if the contract is there you must conform to the contract and
thus call dispose , you might discuss for yourself if the creator of the
object did a good job if he / she implemented the interface in a object
that does not use anny unmanaged resources , but this is still no reasson
not to call dispose on the object .

regards

Michel Posseth [MCP]
 
Michel,

Try this dispose

\\\
Module Module1
Sub Main()
Dim Michel As New Wabash
Michel.Dispose()
End Sub
End Module
Public Class Wabash
Public a As String
Public Sub Dispose()
a = a + "onzin"
Dispose()
End Sub
End Class
///

Cor
 
Michel,

The previous is to show that not every dispose should be derived from
component

But the in the message was with dots in fact this one.
There is a warning at the dispose.

\\\
Module Module1
Sub Main()
Dim Michel As System.Data.SqlClient.SqlCommand
Try
Dim a = Michel.ExecuteScalar
Michel = New System.Data.SqlClient.SqlCommand
Catch ex As Exception
'Handle the error
Finally
Michel.Dispose()
End Try
End Sub
End Module
///

The SQL command does not hold any unmanaged resource by the way, so the only
benefit for some can be that some early cleaning will be done at programming
time and not at finalize time by the GC if the dispose method would be
invoked. But that is a complete other discussion.
Before you write it, I advice to use "Using" in this kind of situations, and
I did in that thread.

Cor
 
Hello Cor ,

Obviously i am talking about every object that exposes the idisposable
interface

If someone calls a custom method Dispose and even bether is filling the
method with BL code he/she is obviously not knowing what he/she is doing

As said before by me and others the Idisposable interface is a contract ,
and a contract you may not break without consequences


Laws and contracts are there to be followed and to prevent anarchy ofcourse
it could be a coders choice to embrase a state of lawlessness and wipe there
asses with contracts
however those people should not be surprised if there programs at one day
stopped working or consume a lot of resources .


Now i show you some code you might remember from some while ago posted in
this newsgroup by a person having a "memory leak" in his app

A:

Public Function CountADComputers(ByVal strADPath As String) As Integer
Dim intCount As Integer
Dim entry As New DirectoryServices.DirectoryEntry(strADPath)
Dim mySearcher As New
System.DirectoryServices.DirectorySearcher(entry)
mySearcher.PageSize = 1000
mySearcher.Filter = "(objectClass=Computer)"
intCount = mySearcher.FindAll.Count
mySearcher.Dispose()
mySearcher = Nothing
entry.Dispose()
entry = Nothing
Return intCount
End Function

is the above code good ? ....................

Wel actually it did look good to me , however this code ( try it if you want
as it is runable code ) in a iteration will never release memory the memory
usage will grow on every call to the above method

This code that i used in my company that does the same thing did not have
this problem

B:


Public Function GetADComputers(ByVal strADPath As String) As Integer
Dim retval As Integer = 0
Using entry As New DirectoryServices.DirectoryEntry(strADPath)
Using mySearcher As New DirectoryServices.DirectorySearcher(entry)
With mySearcher
.PageSize = 1000
.Filter = "(objectClass=Computer)"
End With
Using returnValue As DirectoryServices.SearchResultCollection =
mySearcher.FindAll
retval = returnValue.Count
End Using
End Using
entry.Close()
End Using
Return retval
End Function

What is the differnce ? well i check every interface and sub interface for
the presence of close and the idisposable interface and wrap it in a using
statement

i guess your code would be something like this

C:

Public Function CountADComputers(ByVal strADPath As String) As Integer
Dim intCount As Integer
Dim entry As New DirectoryServices.DirectoryEntry(strADPath)
Dim mySearcher As New
System.DirectoryServices.DirectorySearcher(entry)
mySearcher.PageSize = 1000
mySearcher.Filter = "(objectClass=Computer)"
intCount = mySearcher.FindAll.Count
Return intCount
End Function

wich in fact would work fine as long as you do not call it to much , and
regularly restart the app

But the only version that could be implemented in a long running app and /
or on a computer with not to much resources is version B i have run
thousands of calls to that method without anny problems
while version A would bomb your app after just a few hundred iterations
version C well i guess we both now that answer but version B can be used as
long as you would like it .

The above case is a perfect example of a discussion we had here multiple
times that when a object that exposes a close and / or dispose method these
should be called when finished with it .

Telling someone that it is not necesary is like telling that you do not need
to stop at a red trafic light when you do not see other trafic comming that
might cross your path
you might just have missed that one car or motorcyclist that comes with high
speed to your path .


HTH


And regards


Michel Posseth [MCP]
http://www.linkedin.com/in/michelposseth
 
Michel,

You never see me writing that the dispose method should not be invoked,
especially by Drawing, Sharepoint it is know that it uses many resources.
(The first because it is using those, the latter because most objects are
simply wrappers about com objects). I did not use the Directory Service
(although I used MPF) and I do this from home in the weekend, when I would
use the DirectoryService I would use it only in an Using clause, simply
because I am suspicious about everything that holds LDAP.

In the System.Data namespace, there is taken effort to make it without
unmananaged resources and if not, encapsulate the disposing in the close.

And what happens, when it is about disposing in this newsgroup, it is always
about system data and not about Drawing, DirectoryService, Sharepoint or
Modal Forms.

Have a look at all the classes which inherit component and therefore
implement IDisposable.

Inheritance Hierarchy
System.ComponentModel..::.Component
Microsoft.ManagementConsole.Advanced..::.WaitDialog
Microsoft.VisualBasic.Compatibility.VB6..::.BaseControlArray
System.CodeDom.Compiler..::.CodeDomProvider
System.ComponentModel..::.BackgroundWorker
System.Configuration.Install..::.Installer
System.Data.Common..::.DataAdapter
System.Data.Common..::.DbCommand
System.Data.Common..::.DbCommandBuilder
System.Data.Common..::.DbConnection
System.Diagnostics..::.EventLog
System.Diagnostics..::.EventLogEntry
System.Diagnostics..::.PerformanceCounter
System.Diagnostics..::.Process
System.Diagnostics..::.ProcessModule
System.Diagnostics..::.ProcessThread
System.DirectoryServices..::.DirectoryEntry
System.DirectoryServices..::.DirectorySearcher
System.Drawing.Printing..::.PrintDocument
System.IO..::.FileSystemWatcher
System.IO.Ports..::.SerialPort
System.Management..::.ManagementBaseObject
System.Management..::.ManagementEventWatcher
System.Management..::.ManagementObjectSearcher
System.Media..::.SoundPlayer
System.Messaging..::.Message
System.Messaging..::.MessageQueue
System.Net.NetworkInformation..::.Ping
System.Net..::.WebClient
System.Runtime.Remoting.Services..::.RemotingClientProxy
System.Runtime.Remoting.Services..::.RemotingService
System.ServiceProcess..::.ServiceBase
System.ServiceProcess..::.ServiceController
System.Timers..::.Timer
System.Web.Services.Protocols..::.WebClientProtocol
System.Web.UI.WebControls..::.Style
System.Windows.Forms..::.BindingSource
System.Windows.Forms..::.ColumnHeader
System.Windows.Forms..::.CommonDialog
System.Windows.Forms..::.Control
System.Windows.Forms..::.DataGridColumnStyle
System.Windows.Forms..::.DataGridTableStyle
System.Windows.Forms.Design..::.FolderNameEditor..::.FolderBrowser
System.Windows.Forms..::.ErrorProvider
System.Windows.Forms..::.HelpProvider
System.Windows.Forms..::.ImageList
System.Windows.Forms..::.Menu
System.Windows.Forms..::.NotifyIcon
System.Windows.Forms..::.StatusBarPanel
System.Windows.Forms..::.Timer
System.Windows.Forms..::.ToolBarButton
System.Windows.Forms..::.ToolStripItem
System.Windows.Forms..::.ToolStripPanelRow
System.Windows.Forms..::.ToolTip

Be aware that this are not all, by instance System.Windows.Forms..::.Control
is the base for a bunch of other classes

Do you really mean ,that you are for all the objects that can be created
with these classes, call the dispose or use the using method when they go
out of scoop or when the program close

They all contain that red sign from you.

Be aware I am very suspicious with all classes which I don't know and derive
from component when I don't see them in a designer.

Cor



Michel Posseth said:
Hello Cor ,

Obviously i am talking about every object that exposes the idisposable
interface

If someone calls a custom method Dispose and even bether is filling the
method with BL code he/she is obviously not knowing what he/she is doing

As said before by me and others the Idisposable interface is a contract ,
and a contract you may not break without consequences


Laws and contracts are there to be followed and to prevent anarchy
ofcourse it could be a coders choice to embrase a state of lawlessness and
wipe there asses with contracts
however those people should not be surprised if there programs at one day
stopped working or consume a lot of resources .


Now i show you some code you might remember from some while ago posted in
this newsgroup by a person having a "memory leak" in his app

A:

Public Function CountADComputers(ByVal strADPath As String) As Integer
Dim intCount As Integer
Dim entry As New DirectoryServices.DirectoryEntry(strADPath)
Dim mySearcher As New
System.DirectoryServices.DirectorySearcher(entry)
mySearcher.PageSize = 1000
mySearcher.Filter = "(objectClass=Computer)"
intCount = mySearcher.FindAll.Count
mySearcher.Dispose()
mySearcher = Nothing
entry.Dispose()
entry = Nothing
Return intCount
End Function

is the above code good ? ....................

Wel actually it did look good to me , however this code ( try it if you
want as it is runable code ) in a iteration will never release memory the
memory usage will grow on every call to the above method

This code that i used in my company that does the same thing did not
have this problem

B:


Public Function GetADComputers(ByVal strADPath As String) As Integer
Dim retval As Integer = 0
Using entry As New DirectoryServices.DirectoryEntry(strADPath)
Using mySearcher As New DirectoryServices.DirectorySearcher(entry)
With mySearcher
.PageSize = 1000
.Filter = "(objectClass=Computer)"
End With
Using returnValue As DirectoryServices.SearchResultCollection =
mySearcher.FindAll
retval = returnValue.Count
End Using
End Using
entry.Close()
End Using
Return retval
End Function

What is the differnce ? well i check every interface and sub interface
for the presence of close and the idisposable interface and wrap it in a
using statement

i guess your code would be something like this

C:

Public Function CountADComputers(ByVal strADPath As String) As Integer
Dim intCount As Integer
Dim entry As New DirectoryServices.DirectoryEntry(strADPath)
Dim mySearcher As New
System.DirectoryServices.DirectorySearcher(entry)
mySearcher.PageSize = 1000
mySearcher.Filter = "(objectClass=Computer)"
intCount = mySearcher.FindAll.Count
Return intCount
End Function

wich in fact would work fine as long as you do not call it to much , and
regularly restart the app

But the only version that could be implemented in a long running app and /
or on a computer with not to much resources is version B i have run
thousands of calls to that method without anny problems
while version A would bomb your app after just a few hundred iterations
version C well i guess we both now that answer but version B can be used
as long as you would like it .

The above case is a perfect example of a discussion we had here multiple
times that when a object that exposes a close and / or dispose method
these
should be called when finished with it .

Telling someone that it is not necesary is like telling that you do not
need to stop at a red trafic light when you do not see other trafic
comming that might cross your path
you might just have missed that one car or motorcyclist that comes with
high speed to your path .


HTH


And regards


Michel Posseth [MCP]
http://www.linkedin.com/in/michelposseth












Cor Ligthert said:
Michel,

The previous is to show that not every dispose should be derived from
component

But the in the message was with dots in fact this one.
There is a warning at the dispose.

\\\
Module Module1
Sub Main()
Dim Michel As System.Data.SqlClient.SqlCommand
Try
Dim a = Michel.ExecuteScalar
Michel = New System.Data.SqlClient.SqlCommand
Catch ex As Exception
'Handle the error
Finally
Michel.Dispose()
End Try
End Sub
End Module
///

The SQL command does not hold any unmanaged resource by the way, so the
only benefit for some can be that some early cleaning will be done at
programming time and not at finalize time by the GC if the dispose method
would be invoked. But that is a complete other discussion.
Before you write it, I advice to use "Using" in this kind of situations,
and I did in that thread.

Cor
 
Michel said:
As said before by me and others the Idisposable interface is a contract ,
and a contract you may not break without consequences

The contract says that the class implementing the interface must
implement all methods. There is no contract that all interfaces of an
object must be used or all methods of an interface must be called.

We do not have to call Dispose because there is a contract that
deals with interfaces or the disposable pattern. That's not the reason.

It's always been considered good programming practice to release
ressources ASAP because a ressource might be required otherwise,
sooner or later. It depends on the ressource how soon an error occurs if
this rule is not followed. Therefore every programmer should naturally
be keen on following the rule.

As we have the GC, we need more control over releasing unmanaged
ressources. An author of a class must provide a method for this purpose.
(well, he doesn't have to only if he wants an object that can be a
source for errors). There is no contract that forces him how to do it.

From the client's point of view, a method releasing unmanaged
ressources is just there that, *if* he want to release them _now_, there
is a way to do it. It's still up to the programmer if he makes use of it.
Yes, it would be a fault not to do it in the very most cases,
but the fault would be the same if there was no IDisposable interface,
therefore I don't see a contract emerging from the existence of the
IDisposable interface.

It's nice to have an IDisposable interface in the Framework because
it provides a standard. The benefits of a standard are known.
Yet I still don't see a contract, I only see an offer.

So, I agree with you that it's irresponsible not to implement
IDisposable as the author of a class and not to release ressources ASAP
being the client. Still the only contract that I see and _must_ be
followed is the one mentioned in my first sentence.


Armin
 
Michel,

About what I would use, then it would seeing your code and even more because
of the fact that I now know it wraps Com objects, probably be this

\\\
Imports System.DirectoryServices
Public Function GetADComputers(ByVal strADPath As String) As Integer
Using entry As New DirectoryEntry(strADPath)
Using mySearcher As New DirectorySearcher(entry) With {.PageSize
= 100, .Filter = "(objectClass=Computer)"}
Using returnValue As SearchResultCollection =
mySearcher.FindAll()
Return returnValue.Count
End Using
End Using
entry.Close()
End Using
End Function
///

Cor

Michel Posseth said:
Hello Cor ,

Obviously i am talking about every object that exposes the idisposable
interface

If someone calls a custom method Dispose and even bether is filling the
method with BL code he/she is obviously not knowing what he/she is doing

As said before by me and others the Idisposable interface is a contract ,
and a contract you may not break without consequences


Laws and contracts are there to be followed and to prevent anarchy
ofcourse it could be a coders choice to embrase a state of lawlessness and
wipe there asses with contracts
however those people should not be surprised if there programs at one day
stopped working or consume a lot of resources .


Now i show you some code you might remember from some while ago posted in
this newsgroup by a person having a "memory leak" in his app

A:

Public Function CountADComputers(ByVal strADPath As String) As Integer
Dim intCount As Integer
Dim entry As New DirectoryServices.DirectoryEntry(strADPath)
Dim mySearcher As New
System.DirectoryServices.DirectorySearcher(entry)
mySearcher.PageSize = 1000
mySearcher.Filter = "(objectClass=Computer)"
intCount = mySearcher.FindAll.Count
mySearcher.Dispose()
mySearcher = Nothing
entry.Dispose()
entry = Nothing
Return intCount
End Function

is the above code good ? ....................

Wel actually it did look good to me , however this code ( try it if you
want as it is runable code ) in a iteration will never release memory the
memory usage will grow on every call to the above method

This code that i used in my company that does the same thing did not
have this problem

B:


Public Function GetADComputers(ByVal strADPath As String) As Integer
Dim retval As Integer = 0
Using entry As New DirectoryServices.DirectoryEntry(strADPath)
Using mySearcher As New DirectoryServices.DirectorySearcher(entry)
With mySearcher
.PageSize = 1000
.Filter = "(objectClass=Computer)"
End With
Using returnValue As DirectoryServices.SearchResultCollection =
mySearcher.FindAll
retval = returnValue.Count
End Using
End Using
entry.Close()
End Using
Return retval
End Function

What is the differnce ? well i check every interface and sub interface
for the presence of close and the idisposable interface and wrap it in a
using statement

i guess your code would be something like this

C:

Public Function CountADComputers(ByVal strADPath As String) As Integer
Dim intCount As Integer
Dim entry As New DirectoryServices.DirectoryEntry(strADPath)
Dim mySearcher As New
System.DirectoryServices.DirectorySearcher(entry)
mySearcher.PageSize = 1000
mySearcher.Filter = "(objectClass=Computer)"
intCount = mySearcher.FindAll.Count
Return intCount
End Function

wich in fact would work fine as long as you do not call it to much , and
regularly restart the app

But the only version that could be implemented in a long running app and /
or on a computer with not to much resources is version B i have run
thousands of calls to that method without anny problems
while version A would bomb your app after just a few hundred iterations
version C well i guess we both now that answer but version B can be used
as long as you would like it .

The above case is a perfect example of a discussion we had here multiple
times that when a object that exposes a close and / or dispose method
these
should be called when finished with it .

Telling someone that it is not necesary is like telling that you do not
need to stop at a red trafic light when you do not see other trafic
comming that might cross your path
you might just have missed that one car or motorcyclist that comes with
high speed to your path .


HTH


And regards


Michel Posseth [MCP]
http://www.linkedin.com/in/michelposseth












Cor Ligthert said:
Michel,

The previous is to show that not every dispose should be derived from
component

But the in the message was with dots in fact this one.
There is a warning at the dispose.

\\\
Module Module1
Sub Main()
Dim Michel As System.Data.SqlClient.SqlCommand
Try
Dim a = Michel.ExecuteScalar
Michel = New System.Data.SqlClient.SqlCommand
Catch ex As Exception
'Handle the error
Finally
Michel.Dispose()
End Try
End Sub
End Module
///

The SQL command does not hold any unmanaged resource by the way, so the
only benefit for some can be that some early cleaning will be done at
programming time and not at finalize time by the GC if the dispose method
would be invoked. But that is a complete other discussion.
Before you write it, I advice to use "Using" in this kind of situations,
and I did in that thread.

Cor
 
I agree Armin.

I thing that some people get a little *contract* crazy and forget that when
you design a class and choose to implement an insterface in your class, that
you, the class designer are agreeing to implement all the members declared
in the interface. That in no way causes the *user* of a class to be bound
to calling all the members of the class that were provided because of the
interface.

My favorite example is the Dataset. Now, it makes perfect sense why MS
decided to have the Dataset implement IDisposable, because you may be
reading/writing to an XML file directly and, if so, you'll need a way to get
rid of those resources. And, if you are going to get rid of resources, why
not follow the standard Dispose pattern that is already implemented in so
many other places in the framework? Makes perfect sense.

But, if you are not reading/writing directly to/from a file in your DataSet
and you are using it as a true disconnected type, then it is not holding on
to any resources that need to be released and so, why would you call a
useless method for clean up, when there is no mess?

I think people get way too excited over this topic. It seems pretty straight
forward to me: If a type exposes a Dispose method and you are unfamiliar
with the type, call Dispose. If you are familiar with the type and
understand if/when Dispose is needed, call it only if you need to.

So much has been made about current types exposing Dispose because they
*may* need it in some future implementation of that type, so MS implements
it now, so there is no breaking change later. I think my simple test above
handles that situation too.

-Scott
 
After a time of abscense reading this newsgroup i read again a lot of
Dispose bashing
I can only say "Again ! "  i thought we had discussed this several times

Some facts do not change over time , and if you really think calling dispose
isn`t necesary at all i invite you to write some AD code you will then find
that if you do not dispose the smallest object
your program will consume more and more resources untill it hits your
computers limit  and blows up with a out of memory exception .

I also  read about parrotting blah blah about using Dispose , however fact
is that calling Dispose is described in the documentation as a must ( page
202 of the official core reference guide of VB )

So in short if the contract is there you must conform to the contract and
thus call dispose  , you might discuss for yourself if the creator of the
object did a good job if he / she  implemented the interface   in a object
that does   not use anny unmanaged resources  , but this is still no reasson
not to call dispose on the object .

regards

Michel Posseth [MCP]

It's also in the Framework Design Guidelines book published by
Microsoft Press. But, apparently neither of these official sources is
enough to assuage the debate.

Not that it will matter, but here's another argument for always
calling Dispose. If you think it really doesn't do anything then the
JIT compiler will optimize it out anyway, but if it does, in fact, do
something crucial then you've 1) eliminated one more source of hard to
find bugs or/and 2) made your application perform better. Either way,
what could possibily go wrong by calling Dispose!
 
Hello Brian ,


Exact what i mean , it looks to me like the Dispose bashers just take the
risk of there app causing mayhem on the computers resources just because
they are to lazy to call Dispose .

regards

Michel



"Brian Gideon" <[email protected]> schreef in bericht
After a time of abscense reading this newsgroup i read again a lot of
Dispose bashing
I can only say "Again ! " i thought we had discussed this several times

Some facts do not change over time , and if you really think calling
dispose
isn`t necesary at all i invite you to write some AD code you will then
find
that if you do not dispose the smallest object
your program will consume more and more resources untill it hits your
computers limit and blows up with a out of memory exception .

I also read about parrotting blah blah about using Dispose , however fact
is that calling Dispose is described in the documentation as a must ( page
202 of the official core reference guide of VB )

So in short if the contract is there you must conform to the contract and
thus call dispose , you might discuss for yourself if the creator of the
object did a good job if he / she implemented the interface in a object
that does not use anny unmanaged resources , but this is still no reasson
not to call dispose on the object .

regards

Michel Posseth [MCP]

It's also in the Framework Design Guidelines book published by
Microsoft Press. But, apparently neither of these official sources is
enough to assuage the debate.

Not that it will matter, but here's another argument for always
calling Dispose. If you think it really doesn't do anything then the
JIT compiler will optimize it out anyway, but if it does, in fact, do
something crucial then you've 1) eliminated one more source of hard to
find bugs or/and 2) made your application perform better. Either way,
what could possibily go wrong by calling Dispose!
 
Hello ,

Well i guess you both forget that the idisposable interface only has one
public method ,
so in my homble opinion it is foolish for a coder to implement the interface
if it wouldn`t be needed ( now or in the future )


regards

Michel
 
Michel said:
Hello ,

Well i guess you both forget that the idisposable interface only has one
public method ,

I didn't forget.
so in my homble opinion it is foolish for a coder to implement the interface
if it wouldn`t be needed ( now or in the future )

Yes, no doubts.


Armin
 
Again, think about the DataSet, which *may* need to be disposed, depending
on how you use it. If you need to use it, use it. If not, don't. In
reality, Dispose is not unlike any other property or method in that regard.
Sometimes you *need* to call certain members to do what you *need* and
sometimes you don't.
 
I don't think anyone is bashing Dispose (at least I'm not). I'm simply
saying that it makes good sense to know something about the classes you use
and, to that end, in certain cases I know I don't need Dispose and in others
I know I do. So I call it when I need to, I don't when it's not needed, and
if I'm not sure, I call it and then go find out more about the type.

-Scott


Michel Posseth said:
Hello Brian ,


Exact what i mean , it looks to me like the Dispose bashers just take the
risk of there app causing mayhem on the computers resources just because
they are to lazy to call Dispose .

regards

Michel



"Brian Gideon" <[email protected]> schreef in bericht
After a time of abscense reading this newsgroup i read again a lot of
Dispose bashing
I can only say "Again ! " i thought we had discussed this several times

Some facts do not change over time , and if you really think calling
dispose
isn`t necesary at all i invite you to write some AD code you will then
find
that if you do not dispose the smallest object
your program will consume more and more resources untill it hits your
computers limit and blows up with a out of memory exception .

I also read about parrotting blah blah about using Dispose , however fact
is that calling Dispose is described in the documentation as a must (
page
202 of the official core reference guide of VB )

So in short if the contract is there you must conform to the contract and
thus call dispose , you might discuss for yourself if the creator of the
object did a good job if he / she implemented the interface in a object
that does not use anny unmanaged resources , but this is still no reasson
not to call dispose on the object .

regards

Michel Posseth [MCP]

It's also in the Framework Design Guidelines book published by
Microsoft Press. But, apparently neither of these official sources is
enough to assuage the debate.

Not that it will matter, but here's another argument for always
calling Dispose. If you think it really doesn't do anything then the
JIT compiler will optimize it out anyway, but if it does, in fact, do
something crucial then you've 1) eliminated one more source of hard to
find bugs or/and 2) made your application perform better. Either way,
what could possibily go wrong by calling Dispose!
 
 Either way,
what could possibily go wrong by calling Dispose!

Here's an interesting blog I came across while researching this
futher.

http://blogs.msdn.com/kimhamil/archive/2008/11/05/when-to-call-dispose.aspx

Basically, only one of the prominent figures was in the "avoid calling
dispose" camp. But, personally, I find his arguments weak.

First, he gives the example of the IAsyncResult class returned by
FileStream.BeginRead. It contains a WaitHandle member that implements
IDisposable. An unsuspecting caller may extract the instance from
this member with the sole purpose of calling Dispose without realizing
that the property actually lazily initializes the wait handle to begin
with. The problem here is that IAsyncResult is poorly designed in
that regard and doe not adhere to Microsoft's own published guideline
that states if a class or interface holds (either directly or
indirectly) that it too must implement IDisposable in which case that
implementation could decide which of it's members actually needed to
be disposed.

Second, he gives the example of Windows Forms controls which need not
be disposed in mainstream scenarios, but fails to mention that in most
of those scenarios the Dispose method actually *is* called by the
control containers automatically.

So unless someone has better arguments I'm going to stay in the
"always call dispose" camp with the understanding that there are going
to be a few frindge cases that occur mostly out of poor design
choices.
 
Again, think about the DataSet, which *may* need to be disposed, depending
on how you use it.  If you need to use it, use it.  If not, don't.  In
reality, Dispose is not unlike any other property or method in that regard.
Sometimes you *need* to call certain members to do what you *need* and
sometimes you don't.

Actually, I don't think there is a case where Dispose on a DataSet
does anything interesting. I looked at with Reflector, but perhaps I
looked too hastily. Nevertheless, I actually don't call Dispose on a
DataSet which actually contradicts my "always call dispose" position.
But, I omit the call knowing full well the consequences of my decision
if a future version were to have a more useful implementation. It's
just that I find the probability of that exceedingly low as compared
to say...the SqlCommand class.
 
Here's an interesting blog I came across while researching this
futher.

http://blogs.msdn.com/kimhamil/archive/2008/11/05/when-to-call-dispose.aspx

Basically, only one of the prominent figures was in the "avoid calling
dispose" camp. But, personally, I find his arguments weak.

First, he gives the example of the IAsyncResult class returned by
FileStream.BeginRead. It contains a WaitHandle member that implements
IDisposable. An unsuspecting caller may extract the instance from
this member with the sole purpose of calling Dispose without realizing
that the property actually lazily initializes the wait handle to begin
with. The problem here is that IAsyncResult is poorly designed in
that regard and doe not adhere to Microsoft's own published guideline
that states if a class or interface holds (either directly or
indirectly) that it too must implement IDisposable in which case that
implementation could decide which of it's members actually needed to
be disposed.

Agreed.

Second, he gives the example of Windows Forms controls which need not
be disposed in mainstream scenarios, but fails to mention that in most
of those scenarios the Dispose method actually *is* called by the
control containers automatically.

Yeah, this one struck me as odd... The generated code for a form calls
dispose on all controls and components in it's dispose method. The only time
I call dispose on a form is if it is a dialog:

using (SomeDialogForm sdf = new SomeDialogForm())
{
if (sdf.ShowDialog(this) == DialogResult.OK)
{
// do cool stuff
}
}

I should say, I almost never call dispose directly - I usually just put it in
a using block :)
So unless someone has better arguments I'm going to stay in the
"always call dispose" camp with the understanding that there are going
to be a few frindge cases that occur mostly out of poor design
choices.

Me too.
 
Well actually i do call it i make no exceptions , i write them with using
statements ( wich gives me the advanatage of an extra scope )
in BLS classes where i declared a dataset at root level i call dispose on
the dataset in the BLS class dispose method.

Michel



"Brian Gideon" <[email protected]> schreef in bericht
Again, think about the DataSet, which *may* need to be disposed, depending
on how you use it. If you need to use it, use it. If not, don't. In
reality, Dispose is not unlike any other property or method in that
regard.
Sometimes you *need* to call certain members to do what you *need* and
sometimes you don't.

Actually, I don't think there is a case where Dispose on a DataSet
does anything interesting. I looked at with Reflector, but perhaps I
looked too hastily. Nevertheless, I actually don't call Dispose on a
DataSet which actually contradicts my "always call dispose" position.
But, I omit the call knowing full well the consequences of my decision
if a future version were to have a more useful implementation. It's
just that I find the probability of that exceedingly low as compared
to say...the SqlCommand class.
 
Hello Scott ,

This thread was started because i have the feeling that some people think it
is a bad thing or even bad coding practice to call dispose

We get discussions as "do you call dispose on every forms control" while in
fact this is taken care off by the container ( the documentation even
states that windows forms controls are an exception on the general rule to
calll dispose if availlable ) .

I know that in a lot of objects Dispose isn`t doing annything ( although i
nowadays like the extra scope level hyrarchy it provides when using a using
block ) , so some of you are now saying it is OK not to call dispose if
the method isn`t doing annything , so this means you must check the current
behavior and future behavior of every library you implement just for the
sake of not calling dispose on a object that exposes a Dispose method .

Some tell that if a object is in method level it isn`t needed at all (
cause the GC would save you ) , although i showed some AD code that really
brings your computer down and the GC looks the other way
while your computer is draining on resources this can be solved by just
making one litle dispose call .

If i whould need to decompile every third part object lib to check if it
actually really needs a call to dispose that would be fun to explain to my
manager.

regards

Michel





Scott M. said:
I don't think anyone is bashing Dispose (at least I'm not). I'm simply
saying that it makes good sense to know something about the classes you use
and, to that end, in certain cases I know I don't need Dispose and in
others I know I do. So I call it when I need to, I don't when it's not
needed, and if I'm not sure, I call it and then go find out more about the
type.

-Scott


Michel Posseth said:
Hello Brian ,


Exact what i mean , it looks to me like the Dispose bashers just take the
risk of there app causing mayhem on the computers resources just because
they are to lazy to call Dispose .

regards

Michel



"Brian Gideon" <[email protected]> schreef in bericht
After a time of abscense reading this newsgroup i read again a lot of
Dispose bashing
I can only say "Again ! " i thought we had discussed this several times

Some facts do not change over time , and if you really think calling
dispose
isn`t necesary at all i invite you to write some AD code you will then
find
that if you do not dispose the smallest object
your program will consume more and more resources untill it hits your
computers limit and blows up with a out of memory exception .

I also read about parrotting blah blah about using Dispose , however
fact
is that calling Dispose is described in the documentation as a must (
page
202 of the official core reference guide of VB )

So in short if the contract is there you must conform to the contract
and
thus call dispose , you might discuss for yourself if the creator of the
object did a good job if he / she implemented the interface in a object
that does not use anny unmanaged resources , but this is still no
reasson
not to call dispose on the object .

regards

Michel Posseth [MCP]

It's also in the Framework Design Guidelines book published by
Microsoft Press. But, apparently neither of these official sources is
enough to assuage the debate.

Not that it will matter, but here's another argument for always
calling Dispose. If you think it really doesn't do anything then the
JIT compiler will optimize it out anyway, but if it does, in fact, do
something crucial then you've 1) eliminated one more source of hard to
find bugs or/and 2) made your application perform better. Either way,
what could possibily go wrong by calling Dispose!
 
Dispose exists because the class destructor disappeared which, if well designed, would automatically
cleanup as needed. So instead of leaving the decision on when cleanup needed to be done to the
class writer the responsibility has shifted to the client user of the class. The writer of the
class puts in a Dispose method that the user has to guess whether or not to call.

Now let us consider the possibilities:

1. The application only uses the class a few times and doesn't run very long.
You would assume that it wouldn't matter one way or the other. But what if the class
creates unmanaged items that are not released when the application ends. If the application is used
by many people and the system is not restarted for an extended period the leftover items could
slowly strangle the system.

2. The application runs for a long time and uses the class over and over again.
Now you have to tradeoff a performance hit (calling the Dispose method when it is not
needed) against a possible resource leak (not calling the Dispose method when it is needed).

Conclusion:
If the writer of the class spent the time and energy to implement Dispose it would be
impolite not to call it. Besides, if you call it and it is not needed you can blame it on the class
writer -- but if you don't call it and it is needed it is your neck on the line.

Yes, I call Close if it is available, Dispose if it is available and then set the object to nothing
before it goes out of scope. As I see it, the only open item is whether or not to force garbage
collection.
 
Back
Top