-
How should I manage
staticclasses with disposable items? Are there any rules of thumb? -
Basically, should I refactor and make the following
DisposableDataManagerclassnon-or is it fine to leave everything to
staticGC?
.
public static class DisposableDataManager
{
// ImageList is an 'IDisposable'.
public static ImageList FirstImageList { get; private set; }
public static ImageList SecondImageList { get; private set; }
static DisposableDataManager()
{
FirstImageList = CreateFirstImageList();
SecondImageList = CreateSecondImageList();
}
// ...
}
It really depends on how important it is to you that the resources are disposed. When your application closes, all handles it had open (files, network connections, graphics etc) will be released anyway, so that’s not a problem. It’s more of a problem if you want disposal for a more orderly release – e.g. flushing a stream before closing it. The CLR makes a “best effort” to run finalizers before the process exits, which will in turn call
Disposein some cases – but that’s not something I’d want to rely on for anything important.So in the case of
ImageListobjects, it really shouldn’t be an issue. You definitely won’t leak any resources – the operating system will take care of that.Having said that, I’d still try to refactor – simply because global state tends to be a bad idea. It makes dependencies implicit, and testing harder. How hard would it be to provide the relevant information to each object that needed it at construction time?
(Note: static variables are really associated with an
AppDomainrather than the process as a whole. This makes the whole question more complex in applications whereAppDomains are brought up and down, but I doubt that it’s relevant to your scenario.)