MrPolite
Sep 28th, 2002, 08:04 PM
Why should we use Dispose if we're not "locking" a resource?
When using a Pen in GDI+, why do we dispose it after we are done? why should the graphics object be disposed? they dont lock any resources, do they?:confused:
Slow_Learner
Sep 29th, 2002, 12:07 AM
From what I recall reading, while you don't exactly lock a resource a la the old serial port days, there is a finite number of handles for things and you want to .Dispose or .Close anything you can if you're working with a program that will be running for any length of time.
ms-help://MS.VSCC/MS.MSDNVS/cpguide/html/cpconautomaticmemorymanagement.htm
Releasing Memory for Unmanaged Resources
For the majority of the objects that your application creates, you can rely on the garbage collector to automatically perform the necessary memory management tasks. However, unmanaged resources require explicit cleanup. The most common type of unmanaged resource is an object that wraps an operating system resource, such as a file handle, window handle, or network connection. Although the garbage collector is able to track the lifetime of a managed object that encapsulates an unmanaged resource, it does not have specific knowledge about how to clean up the resource. When you create an object that encapsulates an unmanaged resource, it is recommended that you provide the necessary code to clean up the unmanaged resource in a public Dispose method. By providing a Dispose method, you enable users of your object to explicitly free its memory when they are finished with the object. When you use an object that encapsulates an unmanaged resource, you should be aware of Dispose and call it as necessary. For more information about cleaning up unmanaged resources and an example of a design pattern for implementing Dispose, see Programming for Garbage Collection.