467,906 Members | 1,604 Online
Bytes | Developer Community
New Post

Home Posts Topics Members FAQ

Post your question to a community of 467,906 developers. It's quick & easy.

" //Clean Up managed resources " f&*ck

sorry for my not perfect english

i am really f&*ckin angry

in this common pattern about dispose:
//////////////////////////////////////////////////////////

Public class MyClass:IDisposable
{
private bool IsDisposed=false;
public void Dispose()
{
Dispose(true);
GC.SupressFinalize(this);
}
protected void Dispose(bool Diposing)
{
if(!IsDisposed)
{
if(Disposing)
{
//Clean Up managed resources
}
//Clean up unmanaged resources
}
IsDisposed=true;
}
~MyClass()
{
Dispose(false);
}

}
////////////////////////////

most of things are clear -
there are two ways of calling dispose - one from finalizer (only
unmanaged managed will free automatically
if i do understand) second by Dispose() (managed and unamanaged by
hand) BUT

what the hell " //Clean Up managed resources " mean

pozdrawiam (greetings)
C Kinbote

May 18 '07 #1
  • viewed: 2690
Share:
25 Replies
Koliber,

What this means is that if you the disposing parameter of the Dispose
method is true, then you want to call Dispose on any reference that you have
which implements IDisposable. Say your class had a SqlConnection that it
was holding onto. If the disposing parameter was true, then you would call
Dispose on the connection, otherwise, you would not.
--
- Nicholas Paldino [.NET/C# MVP]
- mv*@spam.guard.caspershouse.com

"Koliber (js)" <pr**************@poczta.onet.plwrote in message
news:11**********************@l77g2000hsb.googlegr oups.com...
sorry for my not perfect english

i am really f&*ckin angry

in this common pattern about dispose:
//////////////////////////////////////////////////////////

Public class MyClass:IDisposable
{
private bool IsDisposed=false;
public void Dispose()
{
Dispose(true);
GC.SupressFinalize(this);
}
protected void Dispose(bool Diposing)
{
if(!IsDisposed)
{
if(Disposing)
{
//Clean Up managed resources
}
//Clean up unmanaged resources
}
IsDisposed=true;
}
~MyClass()
{
Dispose(false);
}

}
////////////////////////////

most of things are clear -
there are two ways of calling dispose - one from finalizer (only
unmanaged managed will free automatically
if i do understand) second by Dispose() (managed and unamanaged by
hand) BUT

what the hell " //Clean Up managed resources " mean

pozdrawiam (greetings)
C Kinbote

May 18 '07 #2
On 18 Maj, 21:03, "Nicholas Paldino [.NET/C# MVP]"
<m...@spam.guard.caspershouse.comwrote:
Koliber,

What this means is that if you the disposing parameter of the Dispose
method is true, then you want to call Dispose on any reference that you have
which implements IDisposable. Say your class had a SqlConnection that it
was holding onto. If the disposing parameter was true, then you would call
Dispose on the connection, otherwise, you would not.
No no no no
Net says to me that SqlConnection is unmanaged resource (resource I
should manage) - you say that
it is managed resource? If so what is unamanaged resource?

K.

May 18 '07 #3
Koliber,

SqlConnection is a managed resource. An example of an unmanaged
resource is a window handle that you obtained by calling unmanaged code, or
a file handle, or a socket handle, or any kind of pointer or handle that you
are holding onto which is not managed by the CLR.
--
- Nicholas Paldino [.NET/C# MVP]
- mv*@spam.guard.caspershouse.com

"Koliber (js)" <pr**************@poczta.onet.plwrote in message
news:11********************@l77g2000hsb.googlegrou ps.com...
On 18 Maj, 21:03, "Nicholas Paldino [.NET/C# MVP]"
<m...@spam.guard.caspershouse.comwrote:
>Koliber,

What this means is that if you the disposing parameter of the Dispose
method is true, then you want to call Dispose on any reference that you
have
which implements IDisposable. Say your class had a SqlConnection that it
was holding onto. If the disposing parameter was true, then you would
call
Dispose on the connection, otherwise, you would not.
No no no no
Net says to me that SqlConnection is unmanaged resource (resource I
should manage) - you say that
it is managed resource? If so what is unamanaged resource?

K.

May 18 '07 #4
On May 18, 11:24 pm, "Koliber (js)" <profesor_kinb...@poczta.onet.pl>
wrote:
On 18 Maj, 21:03, "Nicholas Paldino [.NET/C# MVP]"<m...@spam.guard.caspershouse.comwrote:
Koliber,
What this means is that if you the disposing parameter of the Dispose
method is true, then you want to call Dispose on any reference that you have
which implements IDisposable. Say your class had a SqlConnection that it
was holding onto. If the disposing parameter was true, then you would call
Dispose on the connection, otherwise, you would not.

No no no no
Net says to me that SqlConnection is unmanaged resource (resource I
should manage) - you say that
it is managed resource? If so what is unamanaged resource?

K.
K,

Unmanaged code is such code that is not managed by the CLR.
Handles to files, windows etc. that obtained using unmanaged code
(e.g. by P/Invoke).

SqlConnection uses various of unmanaged code for it's implementation
of the underlying physical connection for example (socket connections,
named pipes etc..)
These kine of unmanaged resources are expensive so developers should
use the Dispose pattern to give the option of cleaning unmanaged
resources that are not in use in a deterministic way. Although it is
not necessary, it is very advisable to clean resources in a
deterministic way since GC is not deterministic.

Cheers,
Moty

May 18 '07 #5
>
Unmanaged code is such code that is not managed by the CLR.
Handles to files, windows etc. that obtained using unmanaged code
(e.g. by P/Invoke).

SqlConnection uses various of unmanaged code for it's implementation
of the underlying physical connection for example (socket connections,
named pipes etc..)
These kine of unmanaged resources are expensive so developers should
use the Dispose pattern to give the option of cleaning unmanaged
resources that are not in use in a deterministic way. Although it is
not necessary, it is very advisable to clean resources in a
deterministic way since GC is not deterministic.

Cheers,
Moty

If sql connection is managed resource
why dispose if called from finaliser in pattern above
should leave it untouched? I do not
understand! I was thinking that finaliser above
should guaraantee that dispose will be fired
if not called by hand by user of an object.

And if sql connection is unmanaged resource
what the hell is managed resource and how
it can be explicite free'd? :(

K

May 18 '07 #6
>
If sql connection is managed resource
why dispose if called from finaliser in pattern above
should leave it untouched? I do not
understand! I was thinking that finaliser above
should guaraantee that dispose will be fired
if not called by hand by user of an object.

And if sql connection is unmanaged resource
what the hell is managed resource and how
it can be explicite free'd? :(

K
So, does enybody do not know? I am angry about that
everybody writes "here you clean managed resource"
but nobody what does it mean (let me say again it is strange
if this resources are gc - managed to clean it by hand)

K

May 19 '07 #7
On May 19, 11:21 am, "Koliber (js)" <profesor_kinb...@poczta.onet.pl>
wrote:
If sql connection is managed resource
why dispose if called from finaliser in pattern above
should leave it untouched? I do not
understand! I was thinking that finaliser above
should guaraantee that dispose will be fired
if not called by hand by user of an object.
And if sql connection is unmanaged resource
what the hell is managed resource and how
it can be explicite free'd? :(
K

So, does enybody do not know? I am angry about that
everybody writes "here you clean managed resource"
but nobody what does it mean (let me say again it is strange
if this resources are gc - managed to clean it by hand)

K
Dear Koliber,

Indeed the finalizer guarantees unmanaged resources disposal, but the
time of the disposal is not guaranteed.

The classes that implement dispose pattern, gives the class users a
way for releasing the resources in a deterministic way.

For instance, the code bellow is not a right way to use resources such
as files or SqlConnection

public void DoSomething()
{

SqlConnection con = new SqlConnection(<con string>);
con.Open();
SqlCommand cmd = con.CreateCommand();
// Here we are done with the connection, we can dispose it's
resources, but we don't...
...
... 1000 lines of time consuming operations...
}

When going out of scope, the GC should collect the con instance but
it's not deterministic when it would.

Why not releasing the resources prior to running the 1000 time
consuming operations?

What if the resource is a file that is not shared.. The file will be
locked for reading and writing until the GC will decide to collect
it.. In these cases, the best practice is to dispose the objects as
soon as possible.

But again, it's just a best practice and you are right that the
unmanaged resources will be freed (If the class developer did
implement a finalizer for this purpose) but I think no convincing
should be done for you to know it's best to call Dispose or use the
'using' statement.

The best way to implement the above code would be:

public void DoSomething()
{

using( SqlConnection con = new SqlConnection(<con string>),
SqlCommand cmd = con.CreateCommand())
{
con.Open();
// do things with the command.
} // At this point, the Dispose method of both the con and cmd
objects is called, even if an exception is thrown..
// At this point, the command and the connection are freed (Maybe
gets back to the connection pool).
...
... 1000 lines of time consuming operations...
}

Don't be angry, it's just c# :)

Moty

May 19 '07 #8
On May 19, 12:33 am, "Koliber (js)" <profesor_kinb...@poczta.onet.pl>
wrote:
If sql connection is managed resource
why dispose if called from finaliser in pattern above
should leave it untouched?
The finalizer is called by the GC. Implementing a finalizer is the
only way to code things that needs to be done at instance collection
time (such as releasing internal unmanaged resources). Since Dispose
methods is responsible for cleaning resources, the finalizer code
usually calls the Dispose method.
Therefore, you are right - it's there to guarantee object disposal if
not called manually. But, again, the GC is not deterministic. The
finalizar can practically call the finalizer 10 minutes after it
really got pinned off... Therefore, manual disposal is a best practice
to make sure that unmanaged resources will not be held for 10 minutes,
for nothing....
And if sql connection is unmanaged resource
what the hell is managed resource and how
it can be explicite free'd? :(
Quote: "In Microsoft Windows terminology, managed code is computer
instructions - that is, "code" - executed by a CLI-compliant virtual
machine, such as Microsoft's .NET Framework Common Language Runtime,
or other CLI implementations from The Mono Project or the DotGNU
Project."

Taken from: http://en.wikipedia.org/wiki/Managed_code

Therefore, SqlConnection is a managed code that uses unmanaged
resources.

Hope this clears things..

Moty
May 19 '07 #9
On 19 Maj, 11:43, Moty Michaely <Moty...@gmail.comwrote:
On May 19, 12:33 am, "Koliber (js)" <profesor_kinb...@poczta.onet.pl>
wrote:
If sql connection is managed resource
why dispose if called from finaliser in pattern above
should leave it untouched?

The finalizer is called by the GC. Implementing a finalizer is the
only way to code things that needs to be done at instance collection
time (such as releasing internal unmanaged resources). Since Dispose
methods is responsible for cleaning resources, the finalizer code
usually calls the Dispose method.
Therefore, you are right - it's there to guarantee object disposal if
not called manually. But, again, the GC is not deterministic. The
finalizar can practically call the finalizer 10 minutes after it
really got pinned off... Therefore, manual disposal is a best practice
to make sure that unmanaged resources will not be held for 10 minutes,
for nothing....
And if sql connection is unmanaged resource
what the hell is managed resource and how
it can be explicite free'd? :(

Quote: "In Microsoft Windows terminology, managed code is computer
instructions - that is, "code" - executed by a CLI-compliant virtual
machine, such as Microsoft's .NET Framework Common Language Runtime,
or other CLI implementations from The Mono Project or the DotGNU
Project."

Taken from:http://en.wikipedia.org/wiki/Managed_code

Therefore, SqlConnection is a managed code that uses unmanaged
resources.

Hope this clears things..

Moty
Sorry but not at all :( - my question I am putting all the time is
not
about managed code (all things you said i do know)
it is about 'managed resource'. What the hell it is? and how is
method
of clearing it? (see dispose pattern in 1st post there are two areas
for cleaning code one for unmanaged resources (clear for me i think -
like
sql connection) and second for the managed resource cleaning i do not
know
what it is.

--
test

May 19 '07 #10
On May 19, 2:03 pm, "Koliber (js)" <profesor_kinb...@poczta.onet.pl>
wrote:
On 19 Maj, 11:43, Moty Michaely <Moty...@gmail.comwrote:
On May 19, 12:33 am, "Koliber (js)" <profesor_kinb...@poczta.onet.pl>
wrote:
If sql connection is managed resource
why dispose if called from finaliser in pattern above
should leave it untouched?
The finalizer is called by the GC. Implementing a finalizer is the
only way to code things that needs to be done at instance collection
time (such as releasing internal unmanaged resources). Since Dispose
methods is responsible for cleaning resources, the finalizer code
usually calls the Dispose method.
Therefore, you are right - it's there to guarantee object disposal if
not called manually. But, again, the GC is not deterministic. The
finalizar can practically call the finalizer 10 minutes after it
really got pinned off... Therefore, manual disposal is a best practice
to make sure that unmanaged resources will not be held for 10 minutes,
for nothing....
And if sql connection is unmanaged resource
what the hell is managed resource and how
it can be explicite free'd? :(
Quote: "In Microsoft Windows terminology, managed code is computer
instructions - that is, "code" - executed by a CLI-compliant virtual
machine, such as Microsoft's .NET Framework Common Language Runtime,
or other CLI implementations from The Mono Project or the DotGNU
Project."
Taken from:http://en.wikipedia.org/wiki/Managed_code
Therefore, SqlConnection is a managed code that uses unmanaged
resources.
Hope this clears things..
Moty

Sorry but not at all :( - my question I am putting all the time is
not
about managed code (all things you said i do know)
it is about 'managed resource'. What the hell it is? and how is
method
of clearing it? (see dispose pattern in 1st post there are two areas
for cleaning code one for unmanaged resources (clear for me i think -
like
sql connection) and second for the managed resource cleaning i do not
know
what it is.

--
test
Hi,

Okay, about unmanaged resources:
Unmanaged resource is code that is invoked in unmanaged way such as
windows API calls.

For example:
Let's imagine that you need to develop in a managed way (.NET class) a
class that creates a file and closes it when it goes out of scope.
And let's also imagine that there is no managed class that doe's that,
so you can't use File.Create static method of the .NET System.IO File
class.

How would you do that?

To do so we will need to use p/Invoke to import windows API methods
for file manipulations.
// Import the CreateFile method from kernel32.dll
[DllImport("Kernel32.dll")]
static extern IntPtr CreateFile(
string filename,
[MarshalAs(UnmanagedType.U4)]FileAccess fileaccess,
[MarshalAs(UnmanagedType.U4)]FileShare fileshare,
int securityattributes,
[MarshalAs(UnmanagedType.U4)]FileMode
creationdisposition,
int flags,
IntPtr template);

// Create text.txt file in the current directory
IntPtr ptr= CreateFile("text.txt",FileAccess.ReadWrite,
FileShare.ReadWrite,0,FileMode.Create,0, IntPtr.Zero);

After we obtained a file handle, we will have to expose methods for
writing or reading from the file.. Let's say that we did.
How would we close the file handle?

There is an API call for closing the file handle (or otherwise, the
file will stay opened until the os decides to release it, sometimes
forever...)
[DllImport("kernel32", SetLastError=true)]
static extern unsafe bool CloseHandle(IntPtr hObject);

So to close the file we will have to call CloseHandle(ptr);

When will we call the CloseHandle? Probably in the finalizer. But,
it's more than logical to allow the users of your class to be able to
close the file before the GC calls the finalizer? Here comes the
Dispose pattern..

It's true that the use of unmanaged code (or unsafe code) is *rarely*
required in C# but there are some situations that require them:
* Dealing with existing structures on disk
* Advanced COM or Platform Invoke (p/Invoke) scenarios that
involve structures with pointers in them
* Performance-critical code

Hope this clears it :)

Moty

May 19 '07 #11
oOn 19 Maj, 13:35, Moty Michaely <Moty...@gmail.comwrote:
On May 19, 2:03 pm, "Koliber (js)" <profesor_kinb...@poczta.onet.pl>
wrote:
On 19 Maj, 11:43, Moty Michaely <Moty...@gmail.comwrote:
On May 19, 12:33 am, "Koliber (js)" <profesor_kinb...@poczta.onet.pl>
wrote:
If sql connection is managed resource
why dispose if called from finaliser in pattern above
should leave it untouched?
The finalizer is called by the GC. Implementing a finalizer is the
only way to code things that needs to be done at instance collection
time (such as releasing internal unmanaged resources). Since Dispose
methods is responsible for cleaning resources, the finalizer code
usually calls the Dispose method.
Therefore, you are right - it's there to guarantee object disposal if
not called manually. But, again, the GC is not deterministic. The
finalizar can practically call the finalizer 10 minutes after it
really got pinned off... Therefore, manual disposal is a best practice
to make sure that unmanaged resources will not be held for 10 minutes,
for nothing....
And if sql connection is unmanaged resource
what the hell is managed resource and how
it can be explicite free'd? :(
Quote: "In Microsoft Windows terminology, managed code is computer
instructions - that is, "code" - executed by a CLI-compliant virtual
machine, such as Microsoft's .NET Framework Common Language Runtime,
or other CLI implementations from The Mono Project or the DotGNU
Project."
Taken from:http://en.wikipedia.org/wiki/Managed_code
Therefore, SqlConnection is a managed code that uses unmanaged
resources.
Hope this clears things..
Moty
Sorry but not at all :( - my question I am putting all the time is
not
about managed code (all things you said i do know)
it is about 'managed resource'. What the hell it is? and how is
method
of clearing it? (see dispose pattern in 1st post there are two areas
for cleaning code one for unmanaged resources (clear for me i think -
like
sql connection) and second for the managed resource cleaning i do not
know
what it is.
--
test

Hi,

Okay, about unmanaged resources:
Unmanaged resource is code that is invoked in unmanaged way such as
windows API calls.

For example:
Let's imagine that you need to develop in a managed way (.NET class) a
class that creates a file and closes it when it goes out of scope.
And let's also imagine that there is no managed class that doe's that,
so you can't use File.Create static method of the .NET System.IO File
class.

How would you do that?

To do so we will need to use p/Invoke to import windows API methods
for file manipulations.

// Import the CreateFile method from kernel32.dll
[DllImport("Kernel32.dll")]
static extern IntPtr CreateFile(
string filename,
[MarshalAs(UnmanagedType.U4)]FileAccess fileaccess,
[MarshalAs(UnmanagedType.U4)]FileShare fileshare,
int securityattributes,
[MarshalAs(UnmanagedType.U4)]FileMode
creationdisposition,
int flags,
IntPtr template);

// Create text.txt file in the current directory
IntPtr ptr= CreateFile("text.txt",FileAccess.ReadWrite,
FileShare.ReadWrite,0,FileMode.Create,0, IntPtr.Zero);

After we obtained a file handle, we will have to expose methods for
writing or reading from the file.. Let's say that we did.
How would we close the file handle?

There is an API call for closing the file handle (or otherwise, the
file will stay opened until the os decides to release it, sometimes
forever...)
[DllImport("kernel32", SetLastError=true)]
static extern unsafe bool CloseHandle(IntPtr hObject);

So to close the file we will have to call CloseHandle(ptr);

When will we call the CloseHandle? Probably in the finalizer. But,
it's more than logical to allow the users of your class to be able to
close the file before the GC calls the finalizer? Here comes the
Dispose pattern..

It's true that the use of unmanaged code (or unsafe code) is *rarely*
required in C# but there are some situations that require them:
* Dealing with existing structures on disk
* Advanced COM or Platform Invoke (p/Invoke) scenarios that
involve structures with pointers in them
* Performance-critical code

Hope this clears it :)

Moty
Tnx for answers but you do not talkin abaut what I am askin :( You
still and only talkin about "unmanaged
resource" Can you answer on that:

What is managed resource (there in dispose pattern from 1st post) ?
----------------------------------------------------------------------------------------------------------
How ppl can free such managed resource (wchich i do not understand
what is) ?
-------------------------------------------------------------------------------------------------------------------------

(as i wrote i can think that managed resource could be an every
managed object but as far as
i know such objects are not cleaned by 'commands' - only when
references to it are lost - so
there in didpose pattern it should be some thing diffrent thing - but
what?) It does make me real angry
that nobody writes what it is.

[here now i am goin to eat dinner, be later]


May 19 '07 #12
Oundersn 18 Maj, 22:45, "Nicholas Paldino [.NET/C# MVP]"
<m...@spam.guard.caspershouse.comwrote:
Koliber,

SqlConnection is a managed resource. An example of an unmanaged
resource is a window handle that you obtained by calling unmanaged code, or
a file handle, or a socket handle, or any kind of pointer or handle that you
are holding onto which is not managed by the CLR.

--
- Nicholas Paldino [.NET/C# MVP]
- m...@spam.guard.caspershouse.com
I do not understand why sql connection is as you say managed resource
when file handle
is not managed resource I do not understand the difference between
managed and unmanaged
resource - seem to me that all such resources you are tokin are
unmanaged. They are unamanaged
by GC and with dispose(false) in finalizer should be cleaned - but
maybe i am wrong Shoul there
sql connection be not closed by finalisers and only by dispose - that
is this difference? i do not understand it
good

May 19 '07 #13
On May 19, 3:32 pm, "Koliber (js)" <profesor_kinb...@poczta.onet.pl>
wrote:
Oundersn 18 Maj, 22:45, "Nicholas Paldino [.NET/C# MVP]"<m...@spam.guard.caspershouse.comwrote:
Koliber,
SqlConnection is a managed resource. An example of an unmanaged
resource is a window handle that you obtained by calling unmanaged code, or
a file handle, or a socket handle, or any kind of pointer or handle that you
are holding onto which is not managed by the CLR.
--
- Nicholas Paldino [.NET/C# MVP]
- m...@spam.guard.caspershouse.com

I do not understand why sql connection is as you say managed resource
when file handle
is not managed resource I do not understand the difference between
managed and unmanaged
resource - seem to me that all such resources you are tokin are
unmanaged. They are unamanaged
by GC and with dispose(false) in finalizer should be cleaned - but
maybe i am wrong Shoul there
sql connection be not closed by finalisers and only by dispose - that
is this difference? i do not understand it
good
Hi,

managed resources are indeed SqlConnection and all objects that are
contained in the definition of managed resources.

In the Dispose pattern you posted, you should dispose managed
resources as well.

What if your wrapper class has an SqlConnection as a member variable
and your constructor opens it?

When would you close the connection, if the Dispose method of your
class is called?

If the dispose is called from the finalizer, there is no reason to
call the Dispose methods of the internal classes that needs to be
disposed...

Therefore, to dispose managed disposable objects, you need to do it
manually if your class Dispose method is called.

Hope this clears things better :)

Enjoy your dinner.

Moty

May 19 '07 #14
I had the same doubt you have few days ago.

Now I know that:

- dispose pattern = Dispose + Finalize must be used only with unmanaged code
(as said in the previous post it concerns about P/Invoke, handles, IntPtr
and so far)
- Dispose only that is IDisposable, must be used in all the other cases to
let the "consumer" of a class to release the resource as soon as possible
(he must use using block whenever possible).

All instances of classes that implement IDisposable interfaces are managed
resources and they should be Disposed either manually when you don't need
them anymore or in the Dispose method of the "consumer" class.

The instances of classes that do not implement IDisposable are also managed
resources but the cannot be disposed and are managed directly by the GC: the
only thing you can do to "release" them is setting the reference to null as
for XmlDocument.
HTH,
Luigi.
May 19 '07 #15
On May 19, 3:50 pm, "BLUE" <bluewrote:
I had the same doubt you have few days ago.

Now I know that:

- dispose pattern = Dispose + Finalize must be used only with unmanaged code
(as said in the previous post it concerns about P/Invoke, handles, IntPtr
and so far)
- Dispose only that is IDisposable, must be used in all the other cases to
let the "consumer" of a class to release the resource as soon as possible
(he must use using block whenever possible).

All instances of classes that implement IDisposable interfaces are managed
resources and they should be Disposed either manually when you don't need
them anymore or in the Dispose method of the "consumer" class.

The instances of classes that do not implement IDisposable are also managed
resources but the cannot be disposed and are managed directly by the GC: the
only thing you can do to "release" them is setting the reference to null as
for XmlDocument.

HTH,
Luigi.
Hi,

Luigi explained it better :)

Managed code that implement IDisposable that containes managed classes
that implement IDisposable should dispose those contained classes in
its Dispose method. (In addition, call base.Dispose if overriden).

Moty
May 19 '07 #16
Hey,

Just though I'd drop in to this discussion.

Basically the only thing left unanswered is the difference between
managed and unmanaged in the context of the .NET framework. The
difference is very easy once you understand it (most things are actually ;))

Managed:
- Anything that is native to the framework. Any class that has been
compiled to .NET Intermediate Language.

Unmanaged:
- Anything that is not native to the framework. Any dll, socket, piece
of memory that has been obtained from the Operating system or a third
party non-.NET dll.

So managed and unmanaged have nothing to do with you having to clean
things up. You can call into unmanaged code (for example a function from
dll that came with Windows) and not have anything to clean up afterwards.

So this leaves the difference between a Managed Resource and a Unmanaged
resource.

Managed Resource
- Any piece of memory or file or pointer that is neatly wrapped in a
..NET object. The .NET SqlConnection object for example. Even if the
programmer does not clean this resource up himself, it will eventually
be cleaned up by the Garbage Collector.

Unmanaged Resource
- Any piece of memory or file or pointer that you have a direct
reference to. So if you have WindowHandle in your .NET Forms control,
you have to make sure it is being cleaned up. These resources will not
be closed ot cleaned up by the Garbage Collector, unless the class
holding on to the resources implements at least a Finalizer.

Now on the issue of why we need a dispose function *and* a finalizer.
While the framework does guarantee it will call the finalizer at some
point, it does not guarantee *when* it will call the finalizer. And - on
top of that - in C# code there is no way to call the finalizer directly.
This is where the Dispose method comes is. This method will allow the
programmer to clean up both the managed and the unmanaged resources held
by the object. You might ask why it is not needed to dispose managed
objects from the finalizer (because that is what the additional boolean
parameter to the Dispose function actually manages). This has to do with
the fact that if teh Garbage collector has decided that the object can
be cleaned up, all it's references must also be ready to be cleaned up.
So the Garbage collector will remove these objects in the next GC run.
If you call Dispose on them however, they're alive again for at least
another garbage collector run. So in order to make sure the objects are
cleaned up as fast as possible, you will not call dispose on the managed
resources.

Jesse

May 19 '07 #17
"Koliber (js)" <pr**************@poczta.onet.plschrieb im Newsbeitrag
news:11**********************@l77g2000hsb.googlegr oups.com...
what the hell " //Clean Up managed resources " mean
Shortly it means calling Dispose on any IDisposable referenced by any
instance field of your class.

Christof
May 21 '07 #18
On 19 Maj, 16:15, Jesse Houwing <jesse.houw...@nospam-sogeti.nl>
wrote:
Hey,

Just though I'd drop in to this discussion.

Basically the only thing left unanswered is the difference between
managed and unmanaged in the context of the .NET framework. The
difference is very easy once you understand it (most things are actually ;))

Managed:
- Anything that is native to the framework. Any class that has been
compiled to .NET Intermediate Language.

Unmanaged:
- Anything that is not native to the framework. Any dll, socket, piece
of memory that has been obtained from the Operating system or a third
party non-.NET dll.

So managed and unmanaged have nothing to do with you having to clean
things up. You can call into unmanaged code (for example a function from
dll that came with Windows) and not have anything to clean up afterwards.

So this leaves the difference between a Managed Resource and a Unmanaged
resource.

Managed Resource
- Any piece of memory or file or pointer that is neatly wrapped in a
.NET object. The .NET SqlConnection object for example. Even if the
programmer does not clean this resource up himself, it will eventually
be cleaned up by the Garbage Collector.

Unmanaged Resource
- Any piece of memory or file or pointer that you have a direct
reference to. So if you have WindowHandle in your .NET Forms control,
you have to make sure it is being cleaned up. These resources will not
be closed ot cleaned up by the Garbage Collector, unless the class
holding on to the resources implements at least a Finalizer.

Now on the issue of why we need a dispose function *and* a finalizer.
While the framework does guarantee it will call the finalizer at some
point, it does not guarantee *when* it will call the finalizer. And - on
top of that - in C# code there is no way to call the finalizer directly.
This is where the Dispose method comes is. This method will allow the
programmer to clean up both the managed and the unmanaged resources held
by the object. You might ask why it is not needed to dispose managed
objects from the finalizer (because that is what the additional boolean
parameter to the Dispose function actually manages). This has to do with
the fact that if teh Garbage collector has decided that the object can
be cleaned up, all it's references must also be ready to be cleaned up.
So the Garbage collector will remove these objects in the next GC run.
If you call Dispose on them however, they're alive again for at least
another garbage collector run. So in order to make sure the objects are
cleaned up as fast as possible, you will not call dispose on the managed
resources.

Jesse
So if I understand there it should be like that

Public class MyClass:IDisposable
{
private bool IsDisposed=false;
public void Dispose()
{
Dispose(true);
GC.SupressFinalize(this);
}

protected void Dispose(bool Diposing)
{
if(!IsDisposed)
{
if(Disposing)
{
//Clean Up managed resources
/////////////////////////////////////////////

aMember.Dispose();
bMember.Dispose();
cMember.Dispose();

////////////////////////////////////////////
}
//Clean up unmanaged resources
////////////////////////////////////////////////

some pinvoke resource releases
for example 'paired' api calls
like this from this page

http://safari.oreilly.com/0321174038/app04

//////////////////////////////////////////////
}
IsDisposed=true;
}

~MyClass()
{
Dispose(false);
}
Is that right?
-----------------

Thanx because if so I have done understand important piece of it.

K.
May 22 '07 #19
For examples of IDisposable and Dispose pattern implementation:

http://www.bluebytesoftware.com/blog...3-20c06ae539ae

http://www.eggheadcafe.com/articles/20050625.asp
May 22 '07 #20
Besides, that I couldn't find anthing about paired calls by the link it
looks allright.

You should make the Dispose(bool) virtual, so that inheriting classes can
extend this method.
When you inherit from a class, wich implements the disposing in this way,
you only should override Disposing(bool).

Christof

"Koliber (js)" <pr**************@poczta.onet.plschrieb im Newsbeitrag
news:11*********************@z24g2000prd.googlegro ups.com...
<snip>
So if I understand there it should be like that

Public class MyClass:IDisposable
{
private bool IsDisposed=false;
public void Dispose()
{
Dispose(true);
GC.SupressFinalize(this);
}

protected void Dispose(bool Diposing)
{
if(!IsDisposed)
{
if(Disposing)
{
//Clean Up managed resources
/////////////////////////////////////////////

aMember.Dispose();
bMember.Dispose();
cMember.Dispose();

////////////////////////////////////////////
}
//Clean up unmanaged resources
////////////////////////////////////////////////

some pinvoke resource releases
for example 'paired' api calls
like this from this page

http://safari.oreilly.com/0321174038/app04

//////////////////////////////////////////////
}
IsDisposed=true;
}

~MyClass()
{
Dispose(false);
}
Is that right?
-----------------

Thanx because if so I have done understand important piece of it.

K.


May 22 '07 #21
Is that right?
-----------------

Thanx because if so I have done understand important piece of it.
You've got it now :). As others have said, either mark your class
sealed, or make Dispose(bool) a virtual function.

Ohh and don't forget to test if

aMember.Dispose()

if null or not, before calling Dispose on it. You might be in for a
nasty surprise otherwise.

Jesse

* Koliber (js) wrote, On 22-5-2007 12:39:
On 19 Maj, 16:15, Jesse Houwing <jesse.houw...@nospam-sogeti.nl>
wrote:
>Hey,

Just though I'd drop in to this discussion.

Basically the only thing left unanswered is the difference between
managed and unmanaged in the context of the .NET framework. The
difference is very easy once you understand it (most things are actually ;))

Managed:
- Anything that is native to the framework. Any class that has been
compiled to .NET Intermediate Language.

Unmanaged:
- Anything that is not native to the framework. Any dll, socket, piece
of memory that has been obtained from the Operating system or a third
party non-.NET dll.

So managed and unmanaged have nothing to do with you having to clean
things up. You can call into unmanaged code (for example a function from
dll that came with Windows) and not have anything to clean up afterwards.

So this leaves the difference between a Managed Resource and a Unmanaged
resource.

Managed Resource
- Any piece of memory or file or pointer that is neatly wrapped in a
.NET object. The .NET SqlConnection object for example. Even if the
programmer does not clean this resource up himself, it will eventually
be cleaned up by the Garbage Collector.

Unmanaged Resource
- Any piece of memory or file or pointer that you have a direct
reference to. So if you have WindowHandle in your .NET Forms control,
you have to make sure it is being cleaned up. These resources will not
be closed ot cleaned up by the Garbage Collector, unless the class
holding on to the resources implements at least a Finalizer.

Now on the issue of why we need a dispose function *and* a finalizer.
While the framework does guarantee it will call the finalizer at some
point, it does not guarantee *when* it will call the finalizer. And - on
top of that - in C# code there is no way to call the finalizer directly.
This is where the Dispose method comes is. This method will allow the
programmer to clean up both the managed and the unmanaged resources held
by the object. You might ask why it is not needed to dispose managed
objects from the finalizer (because that is what the additional boolean
parameter to the Dispose function actually manages). This has to do with
the fact that if teh Garbage collector has decided that the object can
be cleaned up, all it's references must also be ready to be cleaned up.
So the Garbage collector will remove these objects in the next GC run.
If you call Dispose on them however, they're alive again for at least
another garbage collector run. So in order to make sure the objects are
cleaned up as fast as possible, you will not call dispose on the managed
resources.

Jesse

So if I understand there it should be like that

Public class MyClass:IDisposable
{
private bool IsDisposed=false;
public void Dispose()
{
Dispose(true);
GC.SupressFinalize(this);
}

protected void Dispose(bool Diposing)
{
if(!IsDisposed)
{
if(Disposing)
{
//Clean Up managed resources
/////////////////////////////////////////////

aMember.Dispose();
bMember.Dispose();
cMember.Dispose();

////////////////////////////////////////////
}
//Clean up unmanaged resources
////////////////////////////////////////////////

some pinvoke resource releases
for example 'paired' api calls
like this from this page

http://safari.oreilly.com/0321174038/app04

//////////////////////////////////////////////
}
IsDisposed=true;
}

~MyClass()
{
Dispose(false);
}
Is that right?
-----------------

Thanx because if so I have done understand important piece of it.

K.

May 22 '07 #22
Public class MyClass:IDisposable
{
private bool IsDisposed=false;
public void Dispose()
{
Dispose(true);
GC.SupressFinalize(this);
}

protected void Dispose(bool Diposing)
{
if(!IsDisposed)
{
if(Disposing)
{
//Clean Up managed resources
/////////////////////////////////////////////

aMember.Dispose();
bMember.Dispose();
cMember.Dispose();

////////////////////////////////////////////
}
//Clean up unmanaged resources
////////////////////////////////////////////////

some pinvoke resource releases
for example 'paired' api calls
like this from this page

http://safari.oreilly.com/0321174038/app04

//////////////////////////////////////////////
}
IsDisposed=true;
}

~MyClass()
{
Dispose(false);
}
Is that right?
-----------------
Yes, that is it.

The difference lies not in whether there is an unmanaged resource. Of
course there is an unmanaged resource. SqlConnection, File, Socket, all of
these have unmanaged resources. The point is to get them cleaned up at the
right time without messing up the garbage collector.

If somebody called Dispose on your object, then it is still reachable.
Therefore you should ask all the resources to dispose as well.

If the finalizer is called on your object, then it is not reachable. If you
have private resources, then they are also not reachable. If they are .NET
classes, then they have their own finalizers which will be run automatically
at about the same time as yours, you do not need to call them. In fact it
would be an error to do so because:

(1) their finalizers might already have run
(2) if you access the object, you will prevent it from being freed during
this garbage collection cycle (resurrection)
(3) if you are subscribed to any events of the object, and resurrect it,
then it will resurrect your object as well

The key thing is, your client only tells you to dispose, so you have to pass
the message along. The garbage collector will tell each managed class to
finalize, so you don't tell other .NET classes when you are being finalized.
But the garbage collector doesn't know about anything except managed
classes, so if you called p/invoke, you need to clean that up yourself.

Ok?
May 22 '07 #23
On 23 Maj, 01:49, "Ben Voigt" <r...@nospam.nospamwrote:
Public class MyClass:IDisposable
{
private bool IsDisposed=false;
public void Dispose()
{
Dispose(true);
GC.SupressFinalize(this);
}
protected void Dispose(bool Diposing)
{
if(!IsDisposed)
{
if(Disposing)
{
//Clean Up managed resources
/////////////////////////////////////////////
aMember.Dispose();
bMember.Dispose();
cMember.Dispose();
////////////////////////////////////////////
}
//Clean up unmanaged resources
////////////////////////////////////////////////
some pinvoke resource releases
for example 'paired' api calls
like this from this page
http://safari.oreilly.com/0321174038/app04
//////////////////////////////////////////////
}
IsDisposed=true;
}
~MyClass()
{
Dispose(false);
}
Is that right?
-----------------

Yes, that is it.

The difference lies not in whether there is an unmanaged resource. Of
course there is an unmanaged resource. SqlConnection, File, Socket, all of
these have unmanaged resources. The point is to get them cleaned up at the
right time without messing up the garbage collector.

If somebody called Dispose on your object, then it is still reachable.
Therefore you should ask all the resources to dispose as well.

If the finalizer is called on your object, then it is not reachable. If you
have private resources, then they are also not reachable. If they are .NET
classes, then they have their own finalizers which will be run automatically
at about the same time as yours, you do not need to call them. In fact it
would be an error to do so because:

(1) their finalizers might already have run
(2) if you access the object, you will prevent it from being freed during
this garbage collection cycle (resurrection)
(3) if you are subscribed to any events of the object, and resurrect it,
then it will resurrect your object as well

The key thing is, your client only tells you to dispose, so you have to pass
the message along. The garbage collector will tell each managed class to
finalize, so you don't tell other .NET classes when you are being finalized.
But the garbage collector doesn't know about anything except managed
classes, so if you called p/invoke, you need to clean that up yourself.

Ok?
Ok, I understand this I think, but I have maybe a little hesittion to
this :>

If my object finalizes oneself and thus my dispose not calls my
members
disposes - who calls them? It is only hesitation because I suppose
that if any objest in this chain has a finaliser who do clean up
for self - not for its members - it also shoud be ok. Is that right?

The other thing I do not understand and I want to ask maybe is:
what is a mechanism of this famous theme: "if you do a finaliser
in your class there memory clean up will work slower because
gc must then block something and waits for something" Can
someone explain it to me maybe?

thanx in advance
K.

May 23 '07 #24

"Koliber (js)" <pr**************@poczta.onet.plwrote in message
news:11*********************@m36g2000hse.googlegro ups.com...
On 23 Maj, 01:49, "Ben Voigt" <r...@nospam.nospamwrote:
Public class MyClass:IDisposable
{
private bool IsDisposed=false;
public void Dispose()
{
Dispose(true);
GC.SupressFinalize(this);
}
protected void Dispose(bool Diposing)
{
if(!IsDisposed)
{
if(Disposing)
{
//Clean Up managed resources
/////////////////////////////////////////////
aMember.Dispose();
bMember.Dispose();
cMember.Dispose();
////////////////////////////////////////////
}
//Clean up unmanaged resources
////////////////////////////////////////////////
some pinvoke resource releases
for example 'paired' api calls
like this from this page
>http://safari.oreilly.com/0321174038/app04
//////////////////////////////////////////////
}
IsDisposed=true;
}
~MyClass()
{
Dispose(false);
}
Is that right?
-----------------

Yes, that is it.

The difference lies not in whether there is an unmanaged resource. Of
course there is an unmanaged resource. SqlConnection, File, Socket, all
of
these have unmanaged resources. The point is to get them cleaned up at
the
right time without messing up the garbage collector.

If somebody called Dispose on your object, then it is still reachable.
Therefore you should ask all the resources to dispose as well.

If the finalizer is called on your object, then it is not reachable. If
you
have private resources, then they are also not reachable. If they are
.NET
classes, then they have their own finalizers which will be run
automatically
at about the same time as yours, you do not need to call them. In fact
it
would be an error to do so because:

(1) their finalizers might already have run
(2) if you access the object, you will prevent it from being freed during
this garbage collection cycle (resurrection)
(3) if you are subscribed to any events of the object, and resurrect it,
then it will resurrect your object as well

The key thing is, your client only tells you to dispose, so you have to
pass
the message along. The garbage collector will tell each managed class to
finalize, so you don't tell other .NET classes when you are being
finalized.
But the garbage collector doesn't know about anything except managed
classes, so if you called p/invoke, you need to clean that up yourself.

Ok?

Ok, I understand this I think, but I have maybe a little hesittion to
this :>

If my object finalizes oneself and thus my dispose not calls my
members
disposes - who calls them? It is only hesitation because I suppose
that if any objest in this chain has a finaliser who do clean up
for self - not for its members - it also shoud be ok. Is that right?

The other thing I do not understand and I want to ask maybe is:
what is a mechanism of this famous theme: "if you do a finaliser
in your class there memory clean up will work slower because
gc must then block something and waits for something" Can
someone explain it to me maybe?
I haven't tried to measure, but I don't think having a finalizer would
really be that much of a problem. The GC already has to block all other
threads while it determines reachability from all the different roots.

The problem is that, if your finalizer does anything at all, it will need
access to its member variables. Then a tracking handle to your object needs
to be placed on the stack and now your object is reachable again. So the GC
can't free your memory. After all, your finalizer could do
some_global_list.Add(this)!
>
thanx in advance
K.

May 23 '07 #25
"Koliber (js)" <pr**************@poczta.onet.plschrieb im Newsbeitrag
news:11*********************@m36g2000hse.googlegro ups.com...
>
The other thing I do not understand and I want to ask maybe is:
what is a mechanism of this famous theme: "if you do a finaliser
in your class there memory clean up will work slower because
gc must then block something and waits for something" Can
someone explain it to me maybe?
This only matters, if Dispose doesn't get called on the instance, or if
Dispose doesn't call GC.SupressFinalize.
So it only matters, if the Finalizer really should run, and then I think
it's worth that. (A small consumption of time for freeing maybe a great
bunch of memory, wich otherwise would be lost, till the end of the
application.)

PS: If you ever will build a class (with finalizer), wich after being
disposed can be reused by calling Open or similar. Don't forget to call
GC.ReRegisterForFinalize while reopening.

Christof
May 23 '07 #26

This discussion thread is closed

Replies have been disabled for this discussion.

Similar topics

10 posts views Thread by Eric-Sebastien Lachance | last post: by
20 posts views Thread by Petter Reinholdtsen | last post: by
1 post views Thread by Craig Kenisston | last post: by
7 posts views Thread by Dave Benjamin | last post: by
By using this site, you agree to our Privacy Policy and Terms of Use.