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


K

Koliber (js)

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
 
Ad

Advertisements

N

Nicholas Paldino [.NET/C# MVP]

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.
 
K

Koliber (js)

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.
 
N

Nicholas Paldino [.NET/C# MVP]

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.
 
M

Moty Michaely

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
 
K

Koliber (js)

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
 
Ad

Advertisements

K

Koliber (js)

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
 
M

Moty Michaely

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
 
M

Moty Michaely

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
 
K

Koliber (js)

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....


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.
 
M

Moty Michaely

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.

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
 
Ad

Advertisements

K

Koliber (js)

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.

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]
 
K

Koliber (js)

Oundersn 18 Maj, 22:45, "Nicholas Paldino [.NET/C# MVP]"
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.
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
 
M

Moty Michaely

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
 
B

BLUE

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.
 
M

Moty Michaely

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
 
Ad

Advertisements

J

Jesse Houwing

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
 
C

Christof Nordiek

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
 
K

Koliber (js)

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?
 
Ad

Advertisements


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