Is it necessary to manually manage the lifetime of System.Drawing objects?
Currently I am employing ‘using’ statements to minimise the lifespan of Brushes and other Drawing objects e.g.
using ( Brush br = new SolidBrush( color ) )
{
// Do something with br
}
Is this necessary or is it safe to let the garbage collector work its magic when and if it needs to?
As a quick aside to the question… what do people think is the cleanest way to achieve this?
It is good to Dispose of System.Drawing object, however if you miss one or two when you get an exception etc, it is not the end of the world. (Other objects like opened files and database connections must always be disposed)
Having lots of “Using” statement all over your code make it more complex to understand. I would therefore in the case of System.Drawing object, consider just calling Dispose() on them at the end of the method.
In the past I have used a class I written “Dustcart”, that implements IDisposable, and contains a collection of objects to dispose. You can then write code like: