That piece of code (the FreeResources method) does whatever is appropriate to free the resources. When it is called by the Dispose method, it frees any .NET resources as you would expect.
When it is called by the destructor, it does not free any .NET resources because you don't know if those resources still exist at that point. Hopefully they were freed earlier by a call to Dispose but if they were not, then the program just needs to wait until they are finalized themselves.
Quote:
|
I was under the impression that you never needed to dispose of managed resources.
|
It is always most efficient to call Dispose for managed resources when you no longer need them. If the program is done with your object, then your object is done with any .NET resources it uses so it should call their Dispose methods.
If you don't, they should still get cleaned up when they are finalized but you don't know when that will happen so it could be a while. (For example, Visual Studio sometimes keeps a file locked even after you close the project that uses it. Then you can't delete the file from Windows Explorer.)
Quote:
|
What is an example of a managed resource to free from page 194?
|
These are any objects that provide a Dispose method. I often use Pen and Brush objects in graphics programs and they provide those methods. For example, a Shape class might draw a shape (circle, rectangle, start, etc.) and have Pen and Brush properties to determine how they are drawn and filled. The cleanup code for the Shape class would call the Pen and Brush Dispose methods.
Quote:
|
Is the distinction between managed and unmanaged here, that managed is a .Net class that implements IDisposable and unmanaged is something from an external API?
|
In a nutshell, yes.
Unmanaged resources are things like window handles, file handles, memory handles, and stuff like that. Often the handle is a number that identifies some object (the window, file, memory, and so on). The garbage collector doesn't know how the number relates to the object it represents (it look like a plain old number to the garbage collector) so it can't know how to free it up.