Search code examples
c#winformsstaticgarbage-collectiondispose

Static disposable objects


  • 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();        
    }

    // ...
}

Solution

  • 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 AppDomains are brought up and down, but I doubt that it's relevant to your scenario.)