Thursday, 30 January 2014

Why it is Important to Dispose of Objects


Unlike the majority of the objects in the .NET Framework, Objects handles are not automatically disposed when your application no longer holds a reference to them. This, as you may have already guessed, can lead to memory allocations that are never released. Over time (application up-time), this could lead to large consumption of memory usage and ultimately an "Out of Memory" exception.
There is however another consideration, which given the vast amounts of RAM computers use as standard, is probably going to be of greater concern - especially if you’re doing a fair amount of custom drawing.

Windows has a limit on the number of Objects handles that a session (i.e., application) is permitted to hold. This value is determined in the system registry, and by default, is set to 10,000 handles (at least this is the case in XP, Vista and 7). This value can be altered by those of you comfortable editing the registry but the maximum that can be applied is 65,536 (Windows 2000 is 16,384).

How to Dispose of These Objects
Disposing of these Objects can be as simple as a call to the Dispose method of the object as follows:
http://www.codeproject.com/images/minus.gif Collapse | Copy Code
Bitmap bitmap = new Bitmap("mypic.bmp");
bitmap.Dispose();
The important thing to remember here is that once you have called the Dispose function, you should not try to access any of the other properties or methods of the disposed object as this will cause an exception. For example, the following would cause you problems:
http://www.codeproject.com/images/minus.gif Collapse | Copy Code
Bitmap bitmap = new Bitmap("mypic.bmp");
bitmap.Dispose();
bitmap.Save("mypic.bmp");
When to Dispose of These Objects
As you can see, it is simple enough to dispose of the object, but the more important question is, when to dispose of it. Well, this of course depends on how and where you declare and use the objects. Consider the following code sample:
http://www.codeproject.com/images/minus.gif Collapse | Copy Code
void EditPhoto(string filename)
{
         Bitmap bitmap = new Bitmap(filename);
         //do some image manipulation here
         bitmap.Save(filename);
         bitmap.Dispose();
}

No comments:

Post a Comment