Destroy Objects How ?

A

Abhishek

hi,

To destroy objects in vb6 we used to write

Set MyObj = Nothing

But how do i destroy objects to clean up memory in vb.net 2005

MyObj.Dispose

is that a right code or i still need to use Set MyObj = Nothing ?

Set MyObj = Nothing
MyObj.Dispose

thank you,
abhishek
 
T

Teemu

is that a right code or i still need to use Set MyObj = Nothing ?

Set MyObj = Nothing
MyObj.Dispose

No, that's totally unnecessary. Setting variable to nothing does not dispose
the object, Dispose method does it.

So, just call object's Dispose method or use it inside Using block.

-Teemu
 
M

Michel Posseth [MCP]

As soon as an object is out of scope it can be collected by the GC , this
can even happen in method scope level
that is why it is in my opinion it is good coding practice to use using
staments for anny object that exposes the idisposable interface
and to implement this interface in custom objects.

So general rule of thumb call dispose or use a using statement if the object
exposes this method , setting to Nothing is not necesary although the
opinions of the pro`s and con`s are wide spread , i have seen Balena code
wich does set objects to Nothing after calling dispose , but i have also
read articles of people who claim that it actually hurts the GC Behavior .

My personal coding style is that of the dispose pattern and and relying on
,managed scope level dispose of objects , this seems to work fine for me

HTH

Michel Posseth
 
A

Armin Zingler

Abhishek said:
hi,

To destroy objects in vb6 we used to write

Set MyObj = Nothing

But how do i destroy objects to clean up memory in vb.net 2005

MyObj.Dispose

is that a right code or i still need to use Set MyObj = Nothing ?

Set MyObj = Nothing
MyObj.Dispose


If you want do clean up ressources ASAP you have to call Dispose and set a
reference to Nothing ASAP. Though, setting a local variable to Nothing right
before the end of the function, does not make sense. Call Dispose only of
you know that the object will not be used anymore. For example, it's not
valid to call e.graphics.dispose in a control's Paint event.


Armin
 
M

Michel Posseth [MCP]

here so more info for the vb6 coder

http://www.dotnet2themax.com/blogs/fbalena/PermaLink,guid,47466ad4-77d4-46b0-a6f9-1d677417ed1f.aspx

I like the shown generic routine in the above link verry much although it
does set the object to Nothing after the call to Dispose i guess that the
writer of the official MS Press Core reference guides VB pre .Net and
VB.Net versions knows what he is doing .

Stephany Young wrote once an answer here in the Groups regarding this topic
that i like verry much

<<<<

You will get as many different answers as ther are programmers, however, the
short answer is No.

Now let me qualify that.

No, you are not required to assign Nothing to an object to 'destroy' it.

In general, when an object goes 'out of scope' it will become available for
garbage collection and the Garbage Collector will 'clean it up' when it gets
around to it.

There are some classes in the Framework where you MUST 'destroy' an instance
of it yourself. Off the top of my head, the WebRequest class is one.

Some classes expose a Dispose method. This indicates that an instance of the
class may make use of some unmanaged resources that need to be cleaned up.
For such objects you need to call the Dispose method of the object rather
than assigning Nothing to the object.

My recommendation is to NOT explicity 'destroy' objects at this stage of
your learning curve.

As you progress you will soon learn which objects you need to 'destroy'
whether it be by assigning Nothing or calling the Dispose method.

That said, you are free to explicity 'destroy' objects, a'la VB6, if you so
choose.

In short what she is saying is that for your own ease of mind do not do it
as it might confuse you and just let the framework handle it for you
in the whole Noting VS not to Nothing battle i think it is a good and valid
answer

My personal opinion is that it doesn`t hurt but that it also doesn`t give
you a benefit in doing so in most situations it just adds a lot of confusion
and in only rare cases you might find a construction where it is necesary
but you might think if the whole construction is written thoroughly, having
said so this is where the nothing can come perfectly valid in its use (
when third party coders messed things up )


regards

Michel Posseth
 
C

Cor Ligthert[MVP]

Abhishek,

There are a lot of different kind of objects although they all inherit from
object, the highest object in .Net.

To destroy an object you have to do nothing, it is done by the managed code
(in fact one of the main addititons to VB6), this happens if an object is
declared in a method as it goes out of scope, sometimes at the end of the
program.

In fact it will be destroyed as there is no reference anymore to it from
whatever place. As long as there is a reference to it, then it will not be
destroyed, how many times you use the close, the dispose methods or set its
own reference to nothing.

As you have a large object and you have declared it globaly, then it can
make sense to set it to nothing, so the object can be destroyed before the
program is at its end.

To remove handles or other kind of unmaneged resources you can mostly call
the method dispose, which is in 20% of the classes (by instance control)
added from components which 20% of the classes is inheriting from (most
control classes), and in those cases is often overridden included the
handling for Idisposable.

Dispose is done implicitly when an object is declared in a using clause or
by most close methods by instance in the AdoNet classes.

Cor
 
T

Tom Shelton

If you want do clean up ressources ASAP you have to call Dispose and set a
reference to Nothing ASAP. Though, setting a local variable to Nothing right
before the end of the function, does not make sense. Call Dispose only of
you know that the object will not be used anymore. For example, it's not
valid to call e.graphics.dispose in a control's Paint event.

Dispose yes, setting to nothing no. As I understand it, the GC is smart
enough to know if a local reference is used again in a method. If not, then
even though the function is still running - the local reference will be
reclaimed.

In other words, setting to nothing ASP - even in the middle of a function
makes little sense either.
 
A

Armin Zingler

Tom said:
In other words, setting to nothing ASP - even in the middle of a
function makes little sense either.

There are not only local variables.


Armin
 
T

Tom Shelton

There are not only local variables.

That's true :) If you dealing with module or class level values, then that
would be the one case where setting an object to nothing makes sense (from a
memory managements standpoint).
 
C

Cor Ligthert[MVP]

Armin,

Why would I "ASAP set a object to Nothing". The GC does, afaik as there is
not a real call to the OS, not start before the end of the method or there
should be real lack of memory.

I found your reply very correct, but this part gives a question to me, so I
am currious to your answer?

Cor
 
A

Armin Zingler

Cor said:
Armin,

Why would I "ASAP set a object to Nothing". The GC does, afaik as
there is not a real call to the OS, not start before the end of the
method or there should be real lack of memory.

I found your reply very correct, but this part gives a question to
me, so I am currious to your answer?

Hi Cor,

like Tom you also refer to local variables, right? Because you write
"end of the method". I did not limit my statement to local variables. The
only thing I wrote about local variables is that it does not make sense to
set local variables to Nothing right before the end of the sub.
I'm not sure if this answers your question.


Armin
 
H

Herfried K. Wagner [MVP]

Abhishek said:
To destroy objects in vb6 we used to write

Set MyObj = Nothing

This did not destroy the object referenced by 'MyObj' necessarily in VB6!
The object has only been destroyed if there was no other reference pointing
to it.
 
M

Michel Posseth [MCP]

Herfried K. Wagner said:
This did not destroy the object referenced by 'MyObj' necessarily in VB6!
The object has only been destroyed if there was no other reference
pointing to it.

AFAIK

This only made sure that the reference count was decreased , this coding
behavior was introduced becuase of a bug in VB 4 or 5 ( i am not sure )
cause setting to Nothing wasn`t necesary in VB6 either , however as it was
considered "Good coding practice" to do so ( as it also didn`t and perhaps
doesn`t ? hurt) due to this bug history , VB coders adopted this way of
coding .

However having said so there could still be a valid reasson to assign a
Nothing / Null pointer to a object in some code constructions

Just my opinion ,

Michel Posseth
http://www.VBDotNetCoder.com
 
C

Cor Ligthert[MVP]

Armin,
The only thing I wrote about local variables is that it does not make
sense to set local variables to Nothing right before the end of the sub.
I'm not sure if this answers your question.

No, as you probably can see is in my message, that I wrote before your
answer to Tom, the same written as in your answer to Tom.

I don't see where it makes sense to set the reference of an (in the method
declared) object to Nothing, that is not only for at the end.

That is the part in your message that makes me curious, where can there be a
reason for that.

Cor
 
C

Cor Ligthert[MVP]

Armin,

I hope you understand this one which I tailored to much.

The meaning of this was:
you. I wrote that message before your discussion thread with Tom.

:)

Cor
 
A

Armin Zingler

Cor said:
Armin,


No, as you probably can see is in my message, that I wrote before your
answer to Tom, the same written as in your answer to Tom.

I don't see where it makes sense to set the reference of an (in the
method declared) object to Nothing, that is not only for at the end.

That is the part in your message that makes me curious, where can
there be a reason for that.

Again you seem to refer to local variables only because you write "(in the
method declared)". I don't know if I ever set a local to Nothing explicitly
but I do with other variables (fields).

It was always considered good programming practice to release resources
ASAP. Also before .Net. If you don't set a reference to Nothing, there's no
chance that the object will be destroyed. This also includes but is not
limited to local variables.

I did not make any distinction between local variables and fields. I only
gave a general hint and said "_If_ you want do clean up ressources ASAP...",
so everyone can decide on his/her own. I did not even give a recommendation
(even if I do recommend this).

I'm sure you know this already,
http://msdn.microsoft.com/en-us/library/f144e03t.aspx
but in the "Releasing Memory" section, in the 1st paragraph, local variables
are also included in "an application's roots". Maybe that's the part of the
misunderstanding. This means, it does make sense to set local variables to
Nothing (unless at the end of the method). For example, you're working with
a huge amount of data (held in a local variable (or better: pointed to
by...)) in the first half of a method only. You can set the local variable
to Nothing before the second half because it may take a long time til the
method ends. Of course, nobody forces anyone to do this. (Just like with
fields)


Armin
 
T

Tom Shelton

Again you seem to refer to local variables only because you write "(in the
method declared)". I don't know if I ever set a local to Nothing explicitly
but I do with other variables (fields).

It was always considered good programming practice to release resources
ASAP. Also before .Net. If you don't set a reference to Nothing, there's no
chance that the object will be destroyed. This also includes but is not
limited to local variables.

I did not make any distinction between local variables and fields. I only
gave a general hint and said "_If_ you want do clean up ressources ASAP...",
so everyone can decide on his/her own. I did not even give a recommendation
(even if I do recommend this).

I'm sure you know this already,
http://msdn.microsoft.com/en-us/library/f144e03t.aspx
but in the "Releasing Memory" section, in the 1st paragraph, local variables
are also included in "an application's roots". Maybe that's the part of the
misunderstanding. This means, it does make sense to set local variables to
Nothing (unless at the end of the method). For example, you're working with
a huge amount of data (held in a local variable (or better: pointed to
by...)) in the first half of a method only. You can set the local variable
to Nothing before the second half because it may take a long time til the
method ends. Of course, nobody forces anyone to do this. (Just like with
fields)

With local variables, it makes no difference (in release mode only). If an
object is not beign read anywhere else in a routine, then it is free to be
collected. You can see this in a simple example:

Module Module1

Sub Main()
Dim t As New TestClass()

GC.Collect()

Console.ReadLine()

End Sub

Class TestClass
Protected Overrides Sub Finalize()
Console.WriteLine("Bye")
End Sub
End Class
End Module

If you run the above in Release mode, you will see the Bye printed before the
call to Console.ReadLine(). Setting a local instance to nothing, never makes
sense from a memory management standpoint. Oh, and by the way - seting the
value to nothing (even after the console.readline()) makes no difference in
the behaviour. The compiler is smart :)

Now, things are different for non local values, module and class level values
- there it can make sense...
 
C

Cor Ligthert[MVP]

Armin,

Thanks for the link, I knew most of what is written, but did not knew the
article, it can save me a lot of time typing when this question comes again
:).

For the rest I thougth it was more like the reply from Tom.

Cor
 
M

Michel Posseth [MCP]

Tom Shelton said:
With local variables, it makes no difference (in release mode only). If
an
object is not beign read anywhere else in a routine, then it is free to be
collected. You can see this in a simple example:

Module Module1

Sub Main()
Dim t As New TestClass()

GC.Collect()

Console.ReadLine()

End Sub

Class TestClass
Protected Overrides Sub Finalize()
Console.WriteLine("Bye")
End Sub
End Class
End Module

If you run the above in Release mode, you will see the Bye printed before
the
call to Console.ReadLine(). Setting a local instance to nothing, never
makes
sense from a memory management standpoint. Oh, and by the way - seting
the
value to nothing (even after the console.readline()) makes no difference
in
the behaviour. The compiler is smart :)

Now, things are different for non local values, module and class level
values
- there it can make sense...

Exactly what i said a few posts above ( the one that nobody seemed to bother
to read :- )

In my homble opinion Armin is right with this statement "If you want do
clean up ressources ASAP you have to call Dispose and set a
reference to Nothing ASAP." just for the simple fact that a GC may happen in
the middle of a method ( an you have just proven this with your example )

AFAIK this is also the reasson why you nowadays have scopes in methods ( If
, loops , using statements )just to optimize the GC behavior and thus
faster relocation of resources if needed .


In the "Practical Guidelines and Best Practices for Microsoft Visual Basic
and Visual C# Developers"
the following pseudo example is given ( out of my head so don`t hang me on
anny mistakes )

Private sub DoSomeStuff ()
Dim Foo as new Foo.Lib
For i = 0 to 10000

if i < 500 then
Foo.DoSome()
elseif i= 500 then
Foo = Nothing
End if
--- DoSome other stuff

Loop
End sub

As you see there are perfectly valid reassons inmaginable , there is also
the situation where you might use a object in some circumstance and not in
another instead of tracking the use of the object with a boolean you can
then just test if is is Nothing or not and so see if it was used in the
routine , and ofcourse for class scoped object pointers setting them to
Nothing is verry handy especially when you implement your own finalize
methods ( or reset methods )

However i fully concur with the stament that it is in 99% of the times not
needed and a waste of keyboard input ( like at the end of a method as Armin
mentioned )
regards

Michel Posseth
 
T

Tom Shelton

Exactly what i said a few posts above ( the one that nobody seemed to bother
to read :- )

In my homble opinion Armin is right with this statement "If you want do
clean up ressources ASAP you have to call Dispose and set a
reference to Nothing ASAP." just for the simple fact that a GC may happen in
the middle of a method ( an you have just proven this with your example )

Calling dispose, sure - set to nothing no. If it's a local resource. IMHO,
you should always call dispose if it is implemented.
AFAIK this is also the reasson why you nowadays have scopes in methods ( If
, loops , using statements )just to optimize the GC behavior and thus
faster relocation of resources if needed .


In the "Practical Guidelines and Best Practices for Microsoft Visual Basic
and Visual C# Developers"
the following pseudo example is given ( out of my head so don`t hang me on
anny mistakes )

Private sub DoSomeStuff ()
Dim Foo as new Foo.Lib
For i = 0 to 10000

if i < 500 then
Foo.DoSome()
elseif i= 500 then
Foo = Nothing
End if
--- DoSome other stuff

Loop
End sub

As you see there are perfectly valid reassons inmaginable , there is also
the situation where you might use a object in some circumstance and not in
another instead of tracking the use of the object with a boolean you can
then just test if is is Nothing or not and so see if it was used in the
routine , and ofcourse for class scoped object pointers setting them to
Nothing is verry handy especially when you implement your own finalize
methods ( or reset methods )

I only mean Nothing (null) from a memory managment perspective - there are
definate algorthmic situations where setting an object to nothing makes sense.
I'm only refering to the setting of nothing in regards to memory managment.
The runtime is smart enough to know if a local object is not read again during
a methods execution, then it is safe to clean it up.
However i fully concur with the stament that it is in 99% of the times not
needed and a waste of keyboard input ( like at the end of a method as Armin
mentioned )

Absolutely true... The 1% is basically, for logic and non local resources.
From a memory management perspective, a local variable never has to be set to
nothing for the GC to do it's job - though I still recommend calling dispose
when an object implements IDisposable...
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top