Often, you will need to allocate a system resource or network resources, etc. Each time you need such a resource, there are three crucial steps to go through:
You will have the resource you use, and then get rid of it. If you forget to properly dispose of it, you create a memory or resource leaks. This is best illustrated through the following models
// Step-A. Allocation of desired object here Font myFont = new Font("Arial", 12.0f); try { // Step-B. use the resource (myFont) here } finally { // Step-C. Dispose your object here if (myFont != null) ((IDisposable)myFont).Dispose(); }
Using allows us to use to compress this to:
//Allocate the desired resource here
using (Font myFont = new Font("Arial", 12.0f))
{
// Use the resource here
}
// The best part is that Disposal is automatic.
No comments:
Post a Comment