473,396 Members | 1,766 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,396 software developers and data experts.

what are unmanaged resources

What is the difference between a managed/unmanaged resource, and how do you
tell which is which? I'm trying to understand how to write some Dispose()
methods, and we are supposed to put code that deals with managed in one
place, and code that deals with unmanaged in another place, but I can't seem
to find anything that clearly explains what that means.

I think if I used a Windows API function to optain a handle, that handle
would be an unmanaged resource. But I can't explain to you exactly why I
think so...

Also, I'm seeing code like this, and I don't know if the Dispose is right?
----
public class ImgViewer : UserControl
{
// bmp can get a value in response to some user actions
private Bitmap bmp;

protected override void Dispose( bool disposing )
{
if( disposing )
{
if (components != null)
{
components.Dispose();
}
}
if ( bmp != null )
bmp.Dispose();

base.Dispose( disposing );
}
}
---

Now, I understand that bmp could be large, and its Dispose() needs to be
called, but is it really unmanaged? If so, how can I tell that?

These are specific examples, but I'd really like a general way to understand
this, so I can know what to do in future.

-Rachel
Nov 17 '05 #1
4 39898
Hi Rachel,
the basic difference between a managed and unmanaged resource is that the
garbage collector knows about all managed resources, at some point in time
the GC will come along and clean up all the memory and resources associated
with a managed object. The GC does not know about unmanaged resources, such
as files, stream and handles, so if you do not clean them up explicitly in
your code then you will end up with memory leaks and locked resources.

The idea behind the IDisposable interface is to let you clean up resources
in a deterministic fashion and clean up unmanaged resources. Even if you do
not have unmanaged resources in your class, you may have large managed
resources like images (which you mentioned) which are taking up valauable
resources such as memory, network connections etc, if you no longer need
these objects then it is nice to clean up all of the resources associated
with the object as soon as possible, rather than waiting until some
indeterminate point in the future when the GC gets called. This code is
placed inside the Dispose functions.

In answer to one of your questions, if you see that an object implements
the IDisposable interface i.e. it has a "public void Dispose()" method then
this is an indication that either the object has unmanaged resources that
need cleaning up or it has some other resources that should be clean up
sooner than later (i.e. by waiting for the garbage collector) and you should
call the Dispose() method when you are finished with the object.

Also anytime you implement the Dispose function you also want to make sure
that you call the Dispose function from your objects finalizer. This is
because you cannot force someone to call your Dispose function, so if they
do not call it then you need to make sure the GC calls it instead. On the
other flip side, if the user calls Dispose() then you can stop the GC from
calling the dispose function in the finalizer because this is unneccessary
and having a finalizer on an object is an expensive operation. You can do
this by calling GC.SupressFinalize(this), which makes sure the object does
not get put on the GC's finalize queue.

In answer to another one of your questions, the Image class has unmanaged
references inside it, but the Image class itself is a managed wrapper around
these items. It has a public Dispose function and a Finalizer which calls
Dispose incase you forget to call it. Therefore even if you don't call
Dispose then unmanaged resources will eventually get cleared up when the GC
calls the objects finalizer method. The big point to note here is WHEN the
GC calls the finalizer. You really have no way to tell when this is going to
happen, so the reason you want to call dispose on the Image object is because
you are using up a lot of memory resources, if you no longer need the object
then calling dipose will free these resources immediately, rather than
waiting for the GC to run.

Your original code you posted had one thing wrong with it, it has the
bmp.Dispose() method outside of the if(disposing) control statement:
public class ImgViewer : UserControl
{
// bmp can get a value in response to some user actions
private Bitmap bmp;

protected override void Dispose( bool disposing )
{
if( disposing )
{
if (components != null)
{
components.Dispose();
}
}
if ( bmp != null )
bmp.Dispose();

base.Dispose( disposing );
}
}
Although not technically wrong because you are checking the object against
null, calls to methods on managed objects should be inside the if(disposing)
statement.

The basic Dispose pattern used goes something like this:

class MyObject : IDisposable
{
//indicates if dispose has already been called
//private bool _disposed = false;

//Finalize method for the object, will call Dispose for us
//to clean up the resources if the user has not called it
~MyObject()
{
//Indicate that the GC called Dispose, not the user
Dispose(false);
}

//This is the public method, it will HOPEFULLY but
//not always be called by users of the class
public void Dispose()
{
//indicate this was NOT called by the Garbage collector
Dispose(true);

//Now we have disposed of all our resources, the GC does not
//need to do anything, stop the finalizer being called
GC.SupressFinalize(this);
}

private void Dispose(bool disposing)
{
//Check to see if we have already disposed the object
//this is necessary because we should be able to call
//Dispose multiple times without throwing an error
if(!disposed)
{
if(disposing)
{
//clean up managed resources
}

//clear up any unmanaged resources - this is safe to
//put outside the disposing check because if the user
//called dispose we want to also clean up unmanaged
//resources, if the GC called Dispose then we only
//want to clean up managed resources
}
}
}
The boolean disposing indicates whether or not the private dispose method
was called by the user or by the Garbage collector. There is an important
reason for this. If the user calls Dispose then you know that all managed
resources pointed to by your object must still be alive i.e. not garbage
collected because your object still has a reference to them so they will not
be collected and someone must have had a reference to your object to call the
public Dispose() method.

If the GC called Dispose then you cannot be sure that the objects which your
object is referencing have not already been garbage collected, so you should
not call any methods on them.

You can be sure that unmanaged resources have not been Garbage collected
because the GC does not know about them so it is safe to clean them up.
If you are inheriting then you need to make the Dispose(bool disposing)
method virtual and make sure you call it from the base class to make sure
resources in the base class are disposed correctly.

Hope that helps, sorry if it was a little long.

Mark R Dawson
http://www.markdawson.org

"Rachel Suddeth" wrote:
What is the difference between a managed/unmanaged resource, and how do you
tell which is which? I'm trying to understand how to write some Dispose()
methods, and we are supposed to put code that deals with managed in one
place, and code that deals with unmanaged in another place, but I can't seem
to find anything that clearly explains what that means.

I think if I used a Windows API function to optain a handle, that handle
would be an unmanaged resource. But I can't explain to you exactly why I
think so...

Also, I'm seeing code like this, and I don't know if the Dispose is right?
----
public class ImgViewer : UserControl
{
// bmp can get a value in response to some user actions
private Bitmap bmp;

protected override void Dispose( bool disposing )
{
if( disposing )
{
if (components != null)
{
components.Dispose();
}
}
if ( bmp != null )
bmp.Dispose();

base.Dispose( disposing );
}
}
---

Now, I understand that bmp could be large, and its Dispose() needs to be
called, but is it really unmanaged? If so, how can I tell that?

These are specific examples, but I'd really like a general way to understand
this, so I can know what to do in future.

-Rachel

Nov 17 '05 #2
Forgot to set the diposed bool to true when the object has been disposed.

private void Dispose(bool disposing)
{
//Check to see if we have already disposed the object
//this is necessary because we should be able to call
//Dispose multiple times without throwing an error
if(!disposed)
{
if(disposing)
{
//clean up managed resources
}

//clear up any unmanaged resources - this is safe to
//put outside the disposing check because if the user
//called dispose we want to also clean up unmanaged
//resources, if the GC called Dispose then we only
//want to clean up managed resources

disposed = true;
}
"Mark R. Dawson" wrote:
Hi Rachel,
the basic difference between a managed and unmanaged resource is that the
garbage collector knows about all managed resources, at some point in time
the GC will come along and clean up all the memory and resources associated
with a managed object. The GC does not know about unmanaged resources, such
as files, stream and handles, so if you do not clean them up explicitly in
your code then you will end up with memory leaks and locked resources.

The idea behind the IDisposable interface is to let you clean up resources
in a deterministic fashion and clean up unmanaged resources. Even if you do
not have unmanaged resources in your class, you may have large managed
resources like images (which you mentioned) which are taking up valauable
resources such as memory, network connections etc, if you no longer need
these objects then it is nice to clean up all of the resources associated
with the object as soon as possible, rather than waiting until some
indeterminate point in the future when the GC gets called. This code is
placed inside the Dispose functions.

In answer to one of your questions, if you see that an object implements
the IDisposable interface i.e. it has a "public void Dispose()" method then
this is an indication that either the object has unmanaged resources that
need cleaning up or it has some other resources that should be clean up
sooner than later (i.e. by waiting for the garbage collector) and you should
call the Dispose() method when you are finished with the object.

Also anytime you implement the Dispose function you also want to make sure
that you call the Dispose function from your objects finalizer. This is
because you cannot force someone to call your Dispose function, so if they
do not call it then you need to make sure the GC calls it instead. On the
other flip side, if the user calls Dispose() then you can stop the GC from
calling the dispose function in the finalizer because this is unneccessary
and having a finalizer on an object is an expensive operation. You can do
this by calling GC.SupressFinalize(this), which makes sure the object does
not get put on the GC's finalize queue.

In answer to another one of your questions, the Image class has unmanaged
references inside it, but the Image class itself is a managed wrapper around
these items. It has a public Dispose function and a Finalizer which calls
Dispose incase you forget to call it. Therefore even if you don't call
Dispose then unmanaged resources will eventually get cleared up when the GC
calls the objects finalizer method. The big point to note here is WHEN the
GC calls the finalizer. You really have no way to tell when this is going to
happen, so the reason you want to call dispose on the Image object is because
you are using up a lot of memory resources, if you no longer need the object
then calling dipose will free these resources immediately, rather than
waiting for the GC to run.

Your original code you posted had one thing wrong with it, it has the
bmp.Dispose() method outside of the if(disposing) control statement:
public class ImgViewer : UserControl
{
// bmp can get a value in response to some user actions
private Bitmap bmp;

protected override void Dispose( bool disposing )
{
if( disposing )
{
if (components != null)
{
components.Dispose();
}
}
if ( bmp != null )
bmp.Dispose();

base.Dispose( disposing );
}
}


Although not technically wrong because you are checking the object against
null, calls to methods on managed objects should be inside the if(disposing)
statement.

The basic Dispose pattern used goes something like this:

class MyObject : IDisposable
{
//indicates if dispose has already been called
//private bool _disposed = false;

//Finalize method for the object, will call Dispose for us
//to clean up the resources if the user has not called it
~MyObject()
{
//Indicate that the GC called Dispose, not the user
Dispose(false);
}

//This is the public method, it will HOPEFULLY but
//not always be called by users of the class
public void Dispose()
{
//indicate this was NOT called by the Garbage collector
Dispose(true);

//Now we have disposed of all our resources, the GC does not
//need to do anything, stop the finalizer being called
GC.SupressFinalize(this);
}

private void Dispose(bool disposing)
{
//Check to see if we have already disposed the object
//this is necessary because we should be able to call
//Dispose multiple times without throwing an error
if(!disposed)
{
if(disposing)
{
//clean up managed resources
}

//clear up any unmanaged resources - this is safe to
//put outside the disposing check because if the user
//called dispose we want to also clean up unmanaged
//resources, if the GC called Dispose then we only
//want to clean up managed resources
}
}
}
The boolean disposing indicates whether or not the private dispose method
was called by the user or by the Garbage collector. There is an important
reason for this. If the user calls Dispose then you know that all managed
resources pointed to by your object must still be alive i.e. not garbage
collected because your object still has a reference to them so they will not
be collected and someone must have had a reference to your object to call the
public Dispose() method.

If the GC called Dispose then you cannot be sure that the objects which your
object is referencing have not already been garbage collected, so you should
not call any methods on them.

You can be sure that unmanaged resources have not been Garbage collected
because the GC does not know about them so it is safe to clean them up.
If you are inheriting then you need to make the Dispose(bool disposing)
method virtual and make sure you call it from the base class to make sure
resources in the base class are disposed correctly.

Hope that helps, sorry if it was a little long.

Mark R Dawson
http://www.markdawson.org

"Rachel Suddeth" wrote:
What is the difference between a managed/unmanaged resource, and how do you
tell which is which? I'm trying to understand how to write some Dispose()
methods, and we are supposed to put code that deals with managed in one
place, and code that deals with unmanaged in another place, but I can't seem
to find anything that clearly explains what that means.

I think if I used a Windows API function to optain a handle, that handle
would be an unmanaged resource. But I can't explain to you exactly why I
think so...

Also, I'm seeing code like this, and I don't know if the Dispose is right?
----
public class ImgViewer : UserControl
{
// bmp can get a value in response to some user actions
private Bitmap bmp;

protected override void Dispose( bool disposing )
{
if( disposing )
{
if (components != null)
{
components.Dispose();
}
}
if ( bmp != null )
bmp.Dispose();

base.Dispose( disposing );
}
}
---

Now, I understand that bmp could be large, and its Dispose() needs to be
called, but is it really unmanaged? If so, how can I tell that?

These are specific examples, but I'd really like a general way to understand
this, so I can know what to do in future.

-Rachel

Nov 17 '05 #3
"Mark R. Dawson" wrote in message
news:BF**********************************@microsof t.com...
Hi Rachel,
the basic difference between a managed and unmanaged resource is that the garbage collector knows about all managed resources... The GC does not
know about unmanaged resources, ...
Yes, I get that, but how do I know whether the GC knows about a resource or
not?
such as files, stream and handles...
Um, so... if I have a FileStream (which I would think of as having a stream)
or a FileInfo (which I would think of as having a file), is that an
unmanaged resource? Or is it another of those managed wrappers that contain
unmanaged resources?

In answer to one of your questions, if you see that an object implements the IDisposable interface i.e. it has a "public void Dispose()" method then this is an indication that either the object has unmanaged resources that
need cleaning up or it has some other resources that should be clean up
sooner than later (i.e. by waiting for the garbage collector) and you should call the Dispose() method when you are finished with the object.


Hmm... but as we discussed with the Bitmap, something that contains
unmanaged resources is not itself an unmanaged resource... in fact I think
if it implements IDisposable, then it is providing info to the GC about how
it should be cleaned up, so we should not put its code outside of the "if
( disposing )" block... right?

Maybe this is the key? Or at least part of it... If a class uses only
ordinary heap/stack memory, then I think we can assume it's managed. If it
uses an operating system resource, then it would be unmanaged unless it
implements IDisposable? Or is there another way a class could tell the GC
how to free its resources without implementing IDisposable?

-Rachel
Nov 17 '05 #4
I think of manage / unmanaged this way:

"managed" refers to anything within the .NET sandbox. This includes all
..NET Framework classes.

"unmanaged" refers to the wilderness outside the .NET sandbox. This
includes anything that is returned to you through calls to Win32 API
functions.

If you never call a Win32 API function, never get back any Win32
"handle" objects, then you're not holding any unmanaged resources.
Files and streams that you open via .NET Framework class methods are
all managed wrappers.

Now, as Mark pointed out, many managed (.NET Framework) objects are
holding unmanaged resources inside them, and you probably want to
Dispose() of them as soon as you can, or at least offer your callers
the opportunity to do so. That's where writing your own Dispose()
method comes in. Essentially, implementing IDisposable() does two
things for you:

1) Allows you to get rid of any resources you grabbed directly from the
operating system behind .NET's back (unmanaged resources).

2) Allows you and your callers to release hefty .NET objects / .NET
objects that are holding precious resources in their grubby little
hands that you / your callers want released _now_.

Thus the "disposing" flag: the code to release unmanaged resources
should always be run, even when your application is shutting down,
because .NET doesn't know how you got those things, and so doesn't know
how to release them without your help. However, there's no point in
releasing those "hefty" objects you're holding onto if your app is
shutting down, or the garbage collector has come to reap you, because
they're going to be collected, or perhaps have already been collected,
anyway.

One addition to Mark's excellent information: if you implement
Dispose() in order to release heavyweight managed objects that you're
holding, be sure to check the "disposed" flag in other places in your
class, so that you throw an exception if your caller tries to do
something dumb like this:

yourObject.Dispose();
yourObject.DoSomething();

After a caller has called Dispose(), you don't want them to be able to
do anything further with the object... you might want to check for that.

Nov 17 '05 #5

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

Similar topics

6
by: Eric | last post by:
for example: SqlConnection is used in my project, how can I know if all connections were closed after open and execution. If some guys forget to close connections after using, how can i check it...
0
by: Fernando Cacciola | last post by:
Hi People, Consider the following: class A : IDisposable { public A ( Stream aResource ) { mResource = aResource ; } public void Dispose() {
2
by: nij | last post by:
Hi, I am developing a C# control for my own use that will be used lots of times on a form. It's inherited direct from Control, so I am doing all the drawing myself... and as there are lots of...
4
by: PromisedOyster | last post by:
There are various contradictory newsgroup postings on this issue, but I would really like a definitive answer from the .NET gurus out there? We have various WinForms that contain multiple Icons...
3
by: DaTurk | last post by:
Hi, I'm implementing the Idisposable pattern and am wondering what the difference it between managed, and unmanaged resources? http://msdn2.microsoft.com/en-us/library/fs2xkftw.aspx in the...
4
by: FAQ server | last post by:
----------------------------------------------------------------------- FAQ Topic - What online resources are available? ----------------------------------------------------------------------- ...
34
by: FAQ server | last post by:
----------------------------------------------------------------------- FAQ Topic - What online resources are available? ----------------------------------------------------------------------- *...
3
by: mitul618 | last post by:
Hi experts, I am writing a financial application which is going to run for days without restart. I understand the use of IDisposible to clean up all resources and preventing memory leak. But in my...
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: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
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
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
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
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
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
0
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...

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.