There are several things to note:
First, objects are automatically garbage-collected. This means, when you click the button the second time, a second SomeClass object will be created, while the first SomeClass object gets ready to be GC-ed. However, GC does not occur immediately. The GC runs on certain intervals (determined by the framework). So, between the time you create the 2nd object (and releasing the 1st one), until the 1st object gets GC-ed, you will see temporary increase of memory usage. However, once the GC runs, the memory usage will go down again.
Second, objects that holds system resources, or unmanaged memory space, must be disposed of immediately after they are out of use. Because, although the object will eventually release system resource or unmanaged memory space that it uses when it gets GC-ed, the GC does not occur immediately. So the object might lockdown certain shared resources, eg. database connection, file handle, etc. Such class typically implements IDisposable, so you can just call it's Dispose method once you are done with it. If you design your own class that uses system resources or unmanaged memory, be sure to implement IDisposable and release those resources in the Dispose method.
Example:
SomeClass myObject = new SomeClass();
// perform operation
myObject.Dispose();
Or, safer still, use C# using syntax:
using (SomeClass myObject = new SomeClass())
{
// perform operation
} // <-- myObject.Dispose() will be called automatically here.
Main Topics
Browse All Topics





by: expertsoulPosted on 2009-11-05 at 19:28:45ID: 25756389
Every time you use 'new' keyword a new object is created and memory is allocated for that object.
In this case if you hit button 3 times, 3 instances of SomeClass will be created. The object will be disposed only when Garbage Collector kicks in.