MSDN recommends disposing any variable of type System.Drawing.Brush before its last reference is released. Otherwise, the resources it is using will not be freed until the garbage collector calls the Brush object's Finalize method.

As we know, local variables are destroyed automatically when the control flow goes out of the scope of the method it belongs. So, is it necessary to dispose a brush object every time if it is local?

Recommended Answers

All 2 Replies

You answered your own question. MSDN recommends it so yes. Anything implementing IDisposable should be disposed when it is no longer needed.

Local variables are not destroyed immediately when they go out of scope but they are no longer accessible.

Calling dispose immediately frees up any resources it can then the GC will, at some point, take the class instance off the heap. By not calling dispose you are leaving resources on the heap until the GC destroys the object, which depends on memory pressure and a number of other factors.

Now introduce a finalizer. Classes implementing a finalizer that follow the IDisposable pattern call GC.SupressFinalize(); to supress the finalizer because the object was explicity cleaned up. If you do not call .Dispose() then when the GC goes to destroy the object it doesn't -- it promotes the object to the next generation of cleanup (technically it does destroy part of it. The thought is the runtime destroys the managed resources and promotes the object then when GC runs for the elevated generation it calls the finalizer to free unmanaged resources). So now you have to wait for GC to run on a higher generation before it truly frees all the resources. There are multiple generations of objects tracked -- longer lived objects are promoted to higher generations so when the .NET runtime needs to reclaim memory it starts at the lowest generation.

So you could probably leave the code as-is and it will work but you're just burning up resources: memory allocated by the object, then the additional CPU time it takes for the GC to track the object, promote it due to unsupressed finalizer, etc.

As we know, local variables are destroyed automatically when the control flow goes out of the scope of the method it belongs. So, is it necessary to dispose a brush object every time if it is local?

While the reference is on the stack, the actual brush object is in the heap. So until the GC gets around to it, the brush still exists (and can be resurrected). If your method gets called a lot (like for a game where you'd want 30+ per second) you'll end up with a lot of brush objects hanging around.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.