473,883 Members | 1,599 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

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.Disp ose();
}
}
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 40072
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.SupressFinal ize(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.Disp ose();
}
}
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.SupressFinal ize(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.Disp ose();
}
}
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.SupressFinal ize(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.Disp ose();
}
}
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.SupressFinal ize(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.Disp ose();
}
}
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******** *************** ***********@mic rosoft.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.Disp ose();
yourObject.DoSo mething();

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
1809
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 out ? best, eric
0
1216
by: Fernando Cacciola | last post by:
Hi People, Consider the following: class A : IDisposable { public A ( Stream aResource ) { mResource = aResource ; } public void Dispose() {
2
1807
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 possible 'bells and whistles' that each control may use, there are lots of brushes, pens, fonts etc that I want to optimise the use of. In other words, lots of unmanaged resources that need to be Disposed after use. The main optimisation that I...
4
2372
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 and Bitmaps that are loaded onto the form dynamically, eg control.Icon = ;. Should we explicitly Dispose of these unmanaged resources when the form closes OR should we leave it up to the garbage collector to remove these (and will it definitively...
3
3307
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 code snippet where it's overloading the Dispose method it disposes of managed and unmanaged resources if disposing == true, and only unmanaged resources if disposing is false. I'm not sure I completely understand. Thank you in advance.
4
326
by: FAQ server | last post by:
----------------------------------------------------------------------- FAQ Topic - What online resources are available? ----------------------------------------------------------------------- Javascript FAQ site, please check first:- http://javascript.faqts.com/ Mozilla JavaScript 1.5 reference:-
34
2426
by: FAQ server | last post by:
----------------------------------------------------------------------- FAQ Topic - What online resources are available? ----------------------------------------------------------------------- * The Official ECMAScript Specification http://www.ecma-international.org/publications/standards/Ecma-262.htm
3
4735
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 case I can't afford to allow GC to run for cleaning up all non-references resources. So, is there any way I can clean up all managed and unmanaged resources after using them to prevent GC. For example assigning null value to reference will still...
0
9793
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 effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
11151
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, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
1
10858
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 Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
9582
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
7974
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5804
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
5996
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
4225
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
3238
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.