Automatic recycling expansion method reasonable?

I write some WinForm user controls that take up a fairly large number of drawings and therefore tend to have many one-time graphic fields lying around (Brushes, Pens, Bitmaps, etc.), and as a result, my control should call Dispose () method Dispose on each of them.

I was worried that I (or the future maintainer) could easily skip the field that needs to be removed, either forgetting to remove it, or not realizing that it implements IDisposable. Thus, I wrote a very simple extension method for Object, which finds and disposes of all IDisposable fields:

static public void DisposeAll(this Object obj) { var disposable = obj.GetType() .GetFields(BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance) .Select(fi => fi.GetValue(obj)) .Where(o => o != null && o is IDisposable) .Cast<IDisposable>(); foreach (var d in disposable) d.Dispose(); } 

My question basically is whether it is wise to do this. I can’t think that this can ruin, but then I’m not very familiar with the internal development of WinForms, and it looks like what is happening (messing with reflection and deletion), which can cause annoying errors in the queue.

+4
source share
5 answers

Usually you do not want to delete all one-time members. For instance. link to the parent form.

+4
source

No, this is not a good approach. Drawing objects created in the OnPaint method must always be local variables wrapped with the using statement. Your approach requires a class declaration, just to store these objects. Painful and ineffective. In addition, you will destroy objects that should never be deleted. For example, like pre-pens and brushes, for example, Pens.Black.

+2
source

It's hard to say if this will work for your particular case; I see the biggest problem in the Dispose() invocations order. If one unmanaged descriptor depends on another, you will have a strange problem with drawing, memory, etc.

IMHO.

+1
source

I think this is dangerous. If you implement this idea, then the object will be deleted (if it can be used), and in some situations, for example, when you need the object to be present, it will disappear.

Automation is good for objects that you are sure that they will not be sent at all.

0
source

You can use FxCop or Code Analysis (Visual Studio 2010 Premium or better).

Rule CA2213 will look for fields that you forgot to dispose of.

0
source

All Articles