Command Binding Memory Leak in WPF

2019-06-21 21:49发布

问题:

When i create a user control that has a CommandBinding to a RoutedUICommand im worried that i get memory leaks.

scenario:

Have a RoutedUICommand as a static in c class where i store my commands Implement the CommandBindings on a user control. Add the user control to the main form. Remove the user control from the main form, set the references to it to null.

The canExecute of the command bindings continues to fire. I dont have a reference to the UserControl so its leaked. and it keeps firing for a long time after the form is closed. (i havent seen it stop) If i force a garbage collect it gets collected (well the canExecute stops firing)

I have a test project that illustrates this. I have a Console.WriteLine in the canExecute that prints out the hash code of the object firing the method. It has a button to add a new user control and one to remove it.

Should i not be concerned with this? the user control does get collected if forced. does this mean it will get collected at the next collection? im noticing performance decrease in our app and am tracking memory leaks etc. we have complicated forms with lots of ui elements and they are hanging around using up processor and memory space, when removed from layout. (we use a lot of commands) I thought once something was removed from the visual tree it could no longer receive routed events. what am i missing?

回答1:

From my understanding, command bindings use something similar to (but not the same as) the WeakEvent pattern.

Basically, a WeakReference is held. This will allow it to work after your reference is gone, but will not prevent your class from getting collected by the GC when nothing else references it.

In short, don't worry - it's working the way it's supposed to work.