How should I manage static
classes with disposable items? Are there any rules of thumb?
Basically, should I refactor and make the following DisposableDataManager
class non-
static
or is it fine to leave everything to GC
?
.
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();
}
// ...
}
In a nutshell, an IDisposable class allows you to explicitly handle the deallocation of resources (typically unmanaged resources or database connections) via the Dispose() method. IDisposable class instances should be created within a "Using" block so as to ensure that the Dispose method is actually called.
You can have the Dispose method in a singleton class but not in a static class.
When you finish using an object that implements IDisposable, you call the object's Dispose or DisposeAsync implementation to explicitly perform cleanup. You can do this in one of two ways: With the C# using statement or declaration ( Using in Visual Basic).
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 Dispose
in some cases - but that's not something I'd want to rely on for anything important.
So in the case of ImageList
objects, 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 AppDomain
rather than the process as a whole. This makes the whole question more complex in applications where AppDomain
s are brought up and down, but I doubt that it's relevant to your scenario.)
You can hook the AppDomain.DomainUnload event and call dispose on anything you want to make sure is cleaned up before you exit.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With