473,507 Members | 5,060 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Lowdown on finalization

Can someone give a reader's digest on finalization of objects in .net
framework.

When do I need to call .Dispose?
What happens when I set the object to Nothing (or null in c#)
What else do I need to know?

Thanks
Nov 20 '05 #1
6 1001
On 2004-02-03, Frank Rizzo <no****@nospam.com> wrote:
Can someone give a reader's digest on finalization of objects in .net
framework.

When do I need to call .Dispose?
When your object manages unmanaged resources (ex: Database connections,
sockets, file handles, os handles, etc). In these cases you'll want
your class to implement the IDisposable interface...

And of course, you'll want to call it on any class that implements it :)
What happens when I set the object to Nothing (or null in c#)
Not much really... It simply releases the reference, and if there are
no other references makes the object eligibale for gc. In the case of
local objects, it should usually be avoided...
What else do I need to know?


http://msdn.microsoft.com/library/de...posemethod.asp

--
Tom Shelton [MVP]
Powered By Gentoo Linux 1.4
"Reality is that which, when you stop believing in it, doesn't go away".
-- Philip K. Dick
Nov 20 '05 #2
Tom Shelton wrote:
On 2004-02-03, Frank Rizzo <no****@nospam.com> wrote:
Can someone give a reader's digest on finalization of objects in .net
framework.

When do I need to call .Dispose?
When your object manages unmanaged resources (ex: Database connections,
sockets, file handles, os handles, etc). In these cases you'll want
your class to implement the IDisposable interface...


So implementing this interface means what? That when the client calls
..Dispose method on my object, I'll release whatever needs to be released?

How is that different from writing a ReleaseResources method where I
release all the resources?

And of course, you'll want to call it on any class that implements it :)

What happens when I set the object to Nothing (or null in c#)

So should I set local objects to Nothing or not? What about class level
variables that I no longer need?

Also, how is Finalize different?


Not much really... It simply releases the reference, and if there are
no other references makes the object eligibale for gc. In the case of
local objects, it should usually be avoided...

What else do I need to know?

http://msdn.microsoft.com/library/de...posemethod.asp


Thanks, this is good stuff. However, is it me or they made it a lot
more complicated than it needs to be? You pass true or false into
Dispose based on the identity of the caller??????? What? Was someone
smoking at ms? I am starting to miss the lack of backspace in vi.
Nov 20 '05 #3
On 2004-02-03, Frank Rizzo <no****@nospam.com> wrote:
Tom Shelton wrote:
On 2004-02-03, Frank Rizzo <no****@nospam.com> wrote:
Can someone give a reader's digest on finalization of objects in .net
framework.

When do I need to call .Dispose?
When your object manages unmanaged resources (ex: Database connections,
sockets, file handles, os handles, etc). In these cases you'll want
your class to implement the IDisposable interface...


So implementing this interface means what? That when the client calls
.Dispose method on my object, I'll release whatever needs to be released?


Yep.
How is that different from writing a ReleaseResources method where I
release all the resources?

There is no difference. IDisposable is just a formalized interface to
accomplish this. Basically, it is a convention.

And of course, you'll want to call it on any class that implements it :)

What happens when I set the object to Nothing (or null in c#)
So should I set local objects to Nothing or not? What about class level
variables that I no longer need?


Local objects don't need to be set to nothing because once the object is
out of scope and no longer referenced it is eligable for GC. In fact,
the JIT can actually optimize the code so that an local object is available
for GC even before the end of the method... Say you have this scenario:

Private Sub MySub()
Dim o As New MyObjectType

o.DoCoolStuff()

' Do a lot of stuff that doesn't have anything to do with o
End Sub

Because the method no longer referes to o, the JIT will make it
available for GC as soon as the call to DoCoolStuff is complete... It
seems in the Beta days setting the object to nothing could actually
interfere with this optimization - but I have since read that the JIT
will actually optimize away the assignment to nothing now.

For class level objects, it would probably be a good idea when they are
no longer needed.
Also, how is Finalize different?


Finalize is a method of object. It's purpose is essentially the same as
Dispose - release resources. The difference is that Finalize is called
by the GC, and should be avoided because it can have a negative impact
on the performance of the GC, because it actually takes two passes to
clean up an object that has overridden Finalize.

What you will usually see is that objects that contain unmanaged
resources will usually implement both IDisposable AND override finalize.
The Dispose implementation, will usually call GC.SuppressFinalize to
remove the object from the finalization queue. This way, you can make
sure that your resources will be released eventually - even if the
client forgets to call dispose. But if they do remember, then you don't
incure the performance hit.

One thing I've taken to doing lately, is actually throw an exception
from the finalize method (or you could use an assertion). This sort of
clues me in to when I haven't managed my resources properly :)


Not much really... It simply releases the reference, and if there are
no other references makes the object eligibale for gc. In the case of
local objects, it should usually be avoided...

What else do I need to know?

http://msdn.microsoft.com/library/de...posemethod.asp


Thanks, this is good stuff. However, is it me or they made it a lot
more complicated than it needs to be? You pass true or false into
Dispose based on the identity of the caller??????? What? Was someone
smoking at ms? I am starting to miss the lack of backspace in vi.


Just covering the bases. For the most part, resource management is
pretty nice in .NET because the runtime can do most of the work for
you... Unfortunately, ever system has it's drawbacks, and there are
times when you have to take a more active role in the process :)

--
Tom Shelton [MVP]
Powered By Gentoo Linux 1.4
The chief cause of problems is solutions.
-- Eric Sevareid
Nov 20 '05 #4
Tom Shelton wrote:
On 2004-02-03, Frank Rizzo <no****@nospam.com> wrote:
Tom Shelton wrote:
On 2004-02-03, Frank Rizzo <no****@nospam.com> wrote:
Can someone give a reader's digest on finalization of objects in .net
framework.

When do I need to call .Dispose?

When your object manages unmanaged resources (ex: Database connections,
sockets, file handles, os handles, etc). In these cases you'll want
your class to implement the IDisposable interface...


So implementing this interface means what? That when the client calls
.Dispose method on my object, I'll release whatever needs to be released?

Yep.

How is that different from writing a ReleaseResources method where I
release all the resources?

There is no difference. IDisposable is just a formalized interface to
accomplish this. Basically, it is a convention.


Ah, I got it.
And of course, you'll want to call it on any class that implements it :)
What happens when I set the object to Nothing (or null in c#)


So should I set local objects to Nothing or not? What about class level
variables that I no longer need?

Local objects don't need to be set to nothing because once the object is
out of scope and no longer referenced it is eligable for GC. In fact,

Ok, let's take 2 concrete examples with an object holding an actual
resource.

private sub MySub()
dim o as Sqlconnection = new SqlConnection("server=x;userid=sa")
o.Open

'do stuff
o.Execute ("drop master")
end sub

Am I right in thinking that GC may not immediately kill the o
(SqlConnection) object, leaving the connection to the database open for
undetermined amount of time?

Assuming I am correct, I'd need to do the following:

....
o.Close
o.Dispose
end Sub

Correct?
Second example, this time in pseudo-code

private sub MySub2()
dim oFile as File = new File("c:\autoexec.bat")
oFile.Open modeExclusiveWrite

oFile.Append ("some extra text")

oFile = Nothing
end sub

In this case, if someone else tried open c:\autoexec.bat, they would
fail because the file is opened for exclusive write and setting oFile to
Nothing has no immediate effect.

In other words, the proper way to do it would be manually call the
Dispose method on the oFile object (i am assuming such a method exists).

Am I right in my assumptions?
Also, how is Finalize different?

Finalize is a method of object. It's purpose is essentially the same as
Dispose - release resources. The difference is that Finalize is called
by the GC, and should be avoided because it can have a negative impact
on the performance of the GC, because it actually takes two passes to
clean up an object that has overridden Finalize.

What you will usually see is that objects that contain unmanaged
resources will usually implement both IDisposable AND override finalize.
The Dispose implementation, will usually call GC.SuppressFinalize to
remove the object from the finalization queue. This way, you can make
sure that your resources will be released eventually - even if the
client forgets to call dispose. But if they do remember, then you don't
incure the performance hit.

One thing I've taken to doing lately, is actually throw an exception
from the finalize method (or you could use an assertion). This sort of
clues me in to when I haven't managed my resources properly :)


Ok, so I am confused again. What should be I cleaning up in Finalize,
if all my resources were released in Dispose?
Nov 20 '05 #5
Frank,
In addition to Tom's comments.

The following articles fully explains the GC along with finalization.

http://msdn.microsoft.com/msdnmag/issues/1100/gci/
http://msdn.microsoft.com/msdnmag/issues/1200/GCI2/

For info on implementing Dispose along with Finalize (you really should
implement both!) see:

http://msdn.microsoft.com/library/de...izeDispose.asp

Hope this helps
Jay
"Frank Rizzo" <no****@nospam.com> wrote in message
news:up**************@TK2MSFTNGP12.phx.gbl...
Can someone give a reader's digest on finalization of objects in .net
framework.

When do I need to call .Dispose?
What happens when I set the object to Nothing (or null in c#)
What else do I need to know?

Thanks

Nov 20 '05 #6
On 2004-02-03, Frank Rizzo <no****@nospam.com> wrote:
Tom Shelton wrote:
On 2004-02-03, Frank Rizzo <no****@nospam.com> wrote:
Tom Shelton wrote:

On 2004-02-03, Frank Rizzo <no****@nospam.com> wrote:
>Can someone give a reader's digest on finalization of objects in .net
>framework.
>
>When do I need to call .Dispose?

When your object manages unmanaged resources (ex: Database connections,
sockets, file handles, os handles, etc). In these cases you'll want
your class to implement the IDisposable interface...

So implementing this interface means what? That when the client calls
.Dispose method on my object, I'll release whatever needs to be released?
Yep.

How is that different from writing a ReleaseResources method where I
release all the resources?

There is no difference. IDisposable is just a formalized interface to
accomplish this. Basically, it is a convention.


Ah, I got it.
And of course, you'll want to call it on any class that implements it :)
>What happens when I set the object to Nothing (or null in c#)

So should I set local objects to Nothing or not? What about class level
variables that I no longer need?

Local objects don't need to be set to nothing because once the object is
out of scope and no longer referenced it is eligable for GC. In fact,

Ok, let's take 2 concrete examples with an object holding an actual
resource.

private sub MySub()
dim o as Sqlconnection = new SqlConnection("server=x;userid=sa")
o.Open

'do stuff
o.Execute ("drop master")
end sub

Am I right in thinking that GC may not immediately kill the o
(SqlConnection) object, leaving the connection to the database open for
undetermined amount of time?
Assuming I am correct, I'd need to do the following:

...
o.Close
o.Dispose
end Sub

Correct?


Correct, except in this case the Dispose is redundant... o.Close
basically does the same thing - release the connection :)

Second example, this time in pseudo-code

private sub MySub2()
dim oFile as File = new File("c:\autoexec.bat")
oFile.Open modeExclusiveWrite

oFile.Append ("some extra text")

oFile = Nothing
end sub

In this case, if someone else tried open c:\autoexec.bat, they would
fail because the file is opened for exclusive write and setting oFile to
Nothing has no immediate effect.

Exactly
In other words, the proper way to do it would be manually call the
Dispose method on the oFile object (i am assuming such a method exists).

Dispose or Close.
Am I right in my assumptions?


Pretty much. GC is indeterminate
Also, how is Finalize different?

Finalize is a method of object. It's purpose is essentially the same as
Dispose - release resources. The difference is that Finalize is called
by the GC, and should be avoided because it can have a negative impact
on the performance of the GC, because it actually takes two passes to
clean up an object that has overridden Finalize.

What you will usually see is that objects that contain unmanaged
resources will usually implement both IDisposable AND override finalize.
The Dispose implementation, will usually call GC.SuppressFinalize to
remove the object from the finalization queue. This way, you can make
sure that your resources will be released eventually - even if the
client forgets to call dispose. But if they do remember, then you don't
incure the performance hit.

One thing I've taken to doing lately, is actually throw an exception
from the finalize method (or you could use an assertion). This sort of
clues me in to when I haven't managed my resources properly :)


Ok, so I am confused again. What should be I cleaning up in Finalize,
if all my resources were released in Dispose?


The same resources you cleaned up in Dispose... Think of it as a back
stop. If the client forgets to call Dispose, then you know that your
resources will get cleaned up - eventually.

Jay, gave some pretty good links on the subject - they may be able to
explain it a little clearer...

--
Tom Shelton [MVP]
Powered By Gentoo Linux 1.4
"He dropped his voice still lower. In the stillness, a fly
would not have dared cleat its throat. "
Nov 20 '05 #7

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

Similar topics

0
1294
by: Tobbi | last post by:
Hi, I have a question about Python object finalization. I would like to be notified when an Object is deallocated. The problem is I would like to do it in C. The only way to register a finalizer I...
11
1384
by: Ted Miller | last post by:
Hi folks. So I'm in the middle of porting a large (previously COM-based) imaging library to .Net. The clients of this library are VB programmers within the company I work for. Their code will be...
1
274
by: JollyK | last post by:
Hello everyone, I have a abstract class called DalBase and in that class I have a couple of methods. One of the method that I have is called BeginTran() and this class initializes a private...
15
2071
by: Rhy Mednick | last post by:
I have a class (let's call it ClassA) that I've written which has events. In another class (let's call it ClassB) I create a collection of ClassA objects. In a third class (ClassC) I create a...
2
1488
by: Frank Rizzo | last post by:
Ok, I need to get this straight in my head. When I implement a destructor in my class, is it guaranteed to be called when the class is destroyed or not? If not, when? Also, does the framework...
6
1900
by: Brian Gideon | last post by:
How have you handled the finalization of thread-specific unmanaged resources? My question pertains specifically to using the DDEML which is a thread-specific API. In other words, every call to...
9
2307
by: Bern McCarty | last post by:
I am porting stuff from MEC++ syntax to the new C++/CLI syntax. Something that we did in the old syntax that proved to be very valuable was to make sure that the finalizer would purposefully...
0
973
by: robert | last post by:
I have (large) disk files connected with ZODB objects and want the disk files to be removed when the Python/ZODB object all finalizes. Is it possible to get a kind of reliable __del__ signal for...
10
2395
by: ask4rishi | last post by:
Hi , We are monitoring the applications using the verboseGC. And in our application we have large number of finalize method. We have observed through VerboaseGC logs that lots of Finalize objects...
0
7223
marktang
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,...
0
7314
Oralloy
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,...
0
7372
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
1
7030
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
0
5623
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...
0
3191
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...
0
3179
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
758
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
0
411
bsmnconsultancy
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...

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.