473,398 Members | 2,113 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,398 software developers and data experts.

GC and Dispose method questions

1) If I do want to keep an object alive throughout the live of an
application, how can I ensure that the GC doesn't clean it up?

2a) How do I determine if an object is a managed or an unmanged resource? I
understand the basic definition for managed resources are resources that the
CLR manage and unmanged resources are resources that the CLR doesn't manage,
however, I haven't been able to find a concrete answer as to what resources
are manage or not manage by the CLR.

2b) This is a following question to 2a. Are String and Int32 managed or
unmanaged resources (since it's not possible to do sTemp.dispose or
iTemp.dispose)? So does doing sTemp = Nothing or iTemp = Nothing release the
resource back to the memory?

3) I created serveral classes and I would like to be able to control when I
dispose it. I've found several articles regarding this topic and in each of
these discussion, the solution is exactly identical. Below is the sample from
the Microsoft MSDN website and is it true that all I need to do is customize
the code below in each of class? Is that the correct implementation?

Public Class Base
Implements IDisposable
' Implement IDisposable.
Public Overloads Sub Dispose() Implements IDisposable.Dispose
Dispose(True)
GC.SuppressFinalize(Me)
End Sub

Protected Overridable Overloads Sub Dispose(ByVal disposing As Boolean)
If disposing Then
' Free other state (managed objects).
End If
' Free your own state (unmanaged objects).
' Set large fields to null.
End Sub

Protected Overrides Sub Finalize()
' Simply call Dispose(False).
Dispose(False)
End Sub
End Class

Nov 21 '05 #1
6 1775
>1) If I do want to keep an object alive throughout the live of an
application, how can I ensure that the GC doesn't clean it up?
You keep a reference to it that will not go out of scope, such as a
Shared field.

2a) How do I determine if an object is a managed or an unmanged resource?
If a class implements IDisposable it generally wraps some kind of
unmanaged resource.

2b) This is a following question to 2a. Are String and Int32 managed or
unmanaged resources (since it's not possible to do sTemp.dispose or
iTemp.dispose)?
They are managed.

So does doing sTemp = Nothing or iTemp = Nothing release the
resource back to the memory?
No, setting a String variable to Nothing just releases the reference
to the string object. If there are no other references to it the GC
will eventually clean it up.

Setting an Integer variable to Nothing is just the same as assigning
it zero.

3) I created serveral classes and I would like to be able to control when I
dispose it. I've found several articles regarding this topic and in each of
these discussion, the solution is exactly identical. Below is the sample from
the Microsoft MSDN website and is it true that all I need to do is customize
the code below in each of class? Is that the correct implementation?


Yes it looks like a good start.

Mattias

--
Mattias Sjögren [MVP] mattias @ mvps.org
http://www.msjogren.net/dotnet/ | http://www.dotnetinterop.com
Please reply only to the newsgroup.
Nov 21 '05 #2
Teresa,

When you do not use directly unmanaged resources yourself (API's) than there
would not be any reason to think about dispose or the GC at all when
Idisposable is implemented in a class.

When you use unmanaged resources yourself, you should use them implementing
IDisposable, from which I saw you has seen that already yourself.

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

I am not using dispose when there is told that Idisposable is implemented.
Except in some special situations where it seems for me that the dispose is
overloaded with extra stuff not really dispossing. By instance the
connection dispose, which takes care for connection pooling as well in Net
version 1x (this will be removed in 2.0).

An object is cleaned up by the GC when it has no reference anymore or when
there is not any reference anymore too it.

A string and integer are values, existing on the stacks. The live as long as
that stack part (method) lives (with the exception in vb of a static
variable, what is in fact global).

Just my thought,

Cor

Nov 21 '05 #3
> 2a) How do I determine if an object is a managed or an unmanged resource?
I
understand the basic definition for managed resources are resources that the CLR manage and unmanged resources are resources that the CLR doesn't manage, however, I haven't been able to find a concrete answer as to what resources are manage or not manage by the CLR.


I haven't found a way other than see if the object has implemented the
IDispose interface and sometimes just for kicks I look at IL just to see
what may be going on.

I *would* call the dispose method if implemented because leaving unmanaged
resources open can effect your program in different ways. Either that or
understand what the effect is of not calling dispose will have on your
program.

One effect is that unmanaged resources do not pressure the GC for collection
like managed objects do. The result is that you could end up with a lot of
unmanaged resources open, putting pressure on the OS. Of course they will be
cleaned up eventually but only when the GC deems it necessary and its basing
its decision on managed memory!

Example, take the following line of code and put it in a plain managed
windows application and make sure it runs on start up (in my example I made
sure F goes immediately out of scope and made sure there were no other
references to F):

- Dim F As IO.FileStream = IO.File.Open("somfile", IO.FileMode.Open,
IO.FileAccess.Write, IO.FileShare.None)

Now try to run a second instance of the application. On my machine I get an
exception. Go ahead and set F = Nothing and it continues to happen. I got
up, went to the bathroom, came back and tried to open a second instance
again and still got an exception (~2 minutes). FileStream has a handle to
the underlying unmanaged file and the code above is depending on the GC to
clean up the object. This situation would be catastrophic on a server
application processing many requests!


Nov 21 '05 #4
Thanks for everyone help!!!! I'm new to .NET and have a very tight deadline
on a .NET proj, I really appreciate all your quick responses.

I have two follow up questions...

1) If my class contains only string and integer members (no DB connection or
file or unmanaged objects), is it still good practice to have a dispose
method to set these member variables to nothing (for string) and 0 (for
integer)?

2) In AMoose's example, if I were to call the dispose (close) method for the
IO.FileStream object, F; then the problem you were talking about wouldn't
occur, correct?

Thank you again!!

"AMoose" wrote:
2a) How do I determine if an object is a managed or an unmanged resource?

I
understand the basic definition for managed resources are resources that

the
CLR manage and unmanged resources are resources that the CLR doesn't

manage,
however, I haven't been able to find a concrete answer as to what

resources
are manage or not manage by the CLR.


I haven't found a way other than see if the object has implemented the
IDispose interface and sometimes just for kicks I look at IL just to see
what may be going on.

I *would* call the dispose method if implemented because leaving unmanaged
resources open can effect your program in different ways. Either that or
understand what the effect is of not calling dispose will have on your
program.

One effect is that unmanaged resources do not pressure the GC for collection
like managed objects do. The result is that you could end up with a lot of
unmanaged resources open, putting pressure on the OS. Of course they will be
cleaned up eventually but only when the GC deems it necessary and its basing
its decision on managed memory!

Example, take the following line of code and put it in a plain managed
windows application and make sure it runs on start up (in my example I made
sure F goes immediately out of scope and made sure there were no other
references to F):

- Dim F As IO.FileStream = IO.File.Open("somfile", IO.FileMode.Open,
IO.FileAccess.Write, IO.FileShare.None)

Now try to run a second instance of the application. On my machine I get an
exception. Go ahead and set F = Nothing and it continues to happen. I got
up, went to the bathroom, came back and tried to open a second instance
again and still got an exception (~2 minutes). FileStream has a handle to
the underlying unmanaged file and the code above is depending on the GC to
clean up the object. This situation would be catastrophic on a server
application processing many requests!


Nov 21 '05 #5
Teresa,

In my opinion

Never call dispose when it is not recommended, by instance for all Draw
objects and for connection.close.

Always close the things where there should be logical a "close" by instance
the file functions.
When you keep a file open by instance it stays locked and when you not
protect that an error will be thrown.

Just my thought,

Cor
Nov 21 '05 #6
> 1) If my class contains only string and integer members (no DB connection
or
file or unmanaged objects), is it still good practice to have a dispose
method to set these member variables to nothing (for string) and 0 (for
integer)?
No. These are managed resources and they will be cleaned up by the GC when
they are unreachable. But if you had a filestream object as a member then
you would want to implement the IDispose pattern so that the underlying file
can be properly closed in time and not left open until the GC gets around to
it.

Its important to realize why IDispose exists, and its because of the
finalize method (the same one used in the IDispose pattern). Mainly the
finalize method exists so that you can be sure clean up of unmanaged
resources will take place and not left up only to the developer. The GC will
notice when an object implements finalize and will call it so resources will
be cleaned up. Unfortunately there are problems with finalize. You are not
sure when finalize will be called, and you have no control over it.
Implementing finalize will force the managed object to live longer. It puts
additional pressure on the GC. In some cases it may never be called. So in
the case of filestream example I showed this would be bad correct?

Also remember that unmanaged resources have no effect on the GC and when it
does garbage collections. Usually handles to unmanaged resources are 32 bits
and to the GC thats not a big deal. Unforunately to the operating system,
the resource in which that handle points to may be very "expensive". My
example shows that exactly. The GC saw no reason to clean up the filestream
object but in the mean time a file is held open and unusable to any
application that wants to use it. The only way for you the developer to
express the importance of that resource is to call Close(or in actuality
Dispose as explained later).

So IDispose exists as marker for objects that indicates to users of the
objects that they may want to call Dispose instead of waiting for the GC to
call finalize, and if the developer doesn't call Dispose the GC will call
finalize sometime in the future. Hopefully the documentation will tell you
enough about why IDispose is implemented and you can make a rational
decision whether to call it or not. If no documentation exists then you
will have to look at the IL or run it through Reflector to see whats going
on and then decide.

Of course whether you call Dispose or not can also depend on the type of
application you are building and the type of resource. I mostly work on
server applications and leaving unmanaged resources open any longer than
they have to be is a detrimental to performance and scalabilty. So "not
calling dispose" in most cases is not an option.

2) In AMoose's example, if I were to call the dispose (close) method for the IO.FileStream object, F; then the problem you were talking about wouldn't
occur, correct?
Correct. And in actuality the filestream Close method is its Dispose method.
Here is the code for filestream's close method afer its run through
Reflector:

Public Overrides Sub Close()
Me.Dispose(True)
GC.nativeSuppressFinalize(Me)
End Sub

Looks familar doesn't it? Go back to your example or to the link Cor sent
you, Close *is* Dispose. So all you are doing with Close (or Dispose) is
deterministically cleaning up unmanaged resources and not waiting for the
GC. And in the example that I have shown waiting for the GC in some cases
can be "not good".
"Teresa" <Te****@discussions.microsoft.com> wrote in message
news:0B**********************************@microsof t.com... Thanks for everyone help!!!! I'm new to .NET and have a very tight deadline on a .NET proj, I really appreciate all your quick responses.

I have two follow up questions...

Thank you again!!

"AMoose" wrote:
2a) How do I determine if an object is a managed or an unmanged
resource? I
understand the basic definition for managed resources are resources
that the
CLR manage and unmanged resources are resources that the CLR doesn't

manage,
however, I haven't been able to find a concrete answer as to what

resources
are manage or not manage by the CLR.


I haven't found a way other than see if the object has implemented the
IDispose interface and sometimes just for kicks I look at IL just to see
what may be going on.

I *would* call the dispose method if implemented because leaving unmanaged resources open can effect your program in different ways. Either that or
understand what the effect is of not calling dispose will have on your
program.

One effect is that unmanaged resources do not pressure the GC for collection like managed objects do. The result is that you could end up with a lot of unmanaged resources open, putting pressure on the OS. Of course they will be cleaned up eventually but only when the GC deems it necessary and its basing its decision on managed memory!

Example, take the following line of code and put it in a plain managed
windows application and make sure it runs on start up (in my example I made sure F goes immediately out of scope and made sure there were no other
references to F):

- Dim F As IO.FileStream = IO.File.Open("somfile", IO.FileMode.Open,
IO.FileAccess.Write, IO.FileShare.None)

Now try to run a second instance of the application. On my machine I get an exception. Go ahead and set F = Nothing and it continues to happen. I got up, went to the bathroom, came back and tried to open a second instance
again and still got an exception (~2 minutes). FileStream has a handle to the underlying unmanaged file and the code above is depending on the GC to clean up the object. This situation would be catastrophic on a server
application processing many requests!


Nov 21 '05 #7

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

Similar topics

4
by: RiteshDotNet | last post by:
..net Frame work 1. Dispose Method what it does ? A. who its call / when it calls ? B. Is it fire automatically ? c. When dispose method is call what it does ? D. Release a Object from memory or...
11
by: Ken Durden | last post by:
I am in search of a comprehensive methodology of using these two object cleanup approaches to get rid of a number of bugs, unpleasantries, and cleanup-ordering issues we currently have in our...
14
by: wobbles | last post by:
Hi Everyone, I've read most of the posts regarding "Dispose" in this NG. I still have some questions. If I declare and use a disposable object (say a DB connection) within a method, is it...
15
by: Sam Sungshik Kong | last post by:
Hello! A disposable object's Dispose() method can be called either explicitly by the programmer or implicitly during finalization. If you call Dispose, the unmanaged resources are released...
16
by: Daniel Mori | last post by:
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?
6
by: Cody Powell | last post by:
Greetings all, I'm wondering if there's a rule of thumb related to objects that implement IDisposable, but whose Dispose() methods are actually marked as protected. If you dig around System.IO,...
14
by: Jonas | last post by:
Hi! I'm developing the middletiers of an ASP.NET application in VB.NET. I've got a business logic layer in which I would like to perform auditing to a database. Instead of making an auditing...
156
by: Dennis | last post by:
Ok, I'm trying to dispose of every object that I create that has a dispose method based on advice from this newsgroup. However, I'm not sure how to dispose of the following object that was created...
1
by: Piotrekk | last post by:
Hi I have few questions which I would like to ask: 1. When would I place my own code to Form1 : Form method 2. When would I create Dispose method by implementing IDispose - what is the...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
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
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...
0
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...
0
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
isladogs
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...

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.