Bill Blogs in C#

Bill Wagner discusses C#, LINQ, and other items of interest

Should you make static variables using Disposable types?
A question with two answers: No, and Occasionally.

I received this question last week:

I'm still working through and enjoying "Effective C#", unfortunately  my job has really intruded for the past 2 months. I'm at Item 18: "Implement the standard Dispose pattern". It says that you should  implement this pattern if your class uses non-memory resources, so I went back to some programs I had written using the Windows Forms lib that use Pens, Fonts, etc.

My First Answer:

Regarding (1): You should never hold unmanaged resources in static variables. It makes the lifetime management more or less impossible to get right.

Regarding (2): This is why I said what I said for (1). There is no reliable way to make this work. If you release the resources in an instance's Dispose() method, any other instance is broken: the resource is gone, but the static member variables are still in scope. If you don't release the resources in some instance method, it's broken because you never release the resources.

If you really want one copy of the unmanaged resources, wrap them in a type that implements the Singleton Pattern.

So, don't store unmanaged resources in static variables. Ever. It won't work.

Upon Further Reflection:

I'm still not sure it's a common pattern, but there might be some instances where this might work.  It's a small resource leak, but there are instances where you don't really care.

Suppose you create some type that needs to hold a resource that implements IDisposable, and that type will have a lifetime that mirrors your application's lifetime. Well, then a static member variable means that you only create one copy of that resource in your application. However, you'll never release that resource. However, it will get cleaned up when your app exits. So, no real problem. It's a little fragile, because you will have quite a bit of work to do if your application changes later and your resource's lifetime no longer matches the application's lifetime.

When I went to implement the pattern I got confused. My questions are
1) In my classes my unmanaged resources are held in static vars. What should I do?
2) Assuming that after understanding #1, I still want to write virtual void Dispose(bool isDisposing): Do I need to free all the references I've new'd to objects when "freeing managed resources"? If yes, how?



Published Monday, October 03, 2005 10:44 PM by wwagner
Filed under: ,

Comments

No Comments