Command Binding Memory Leak in WPF

核能气质少年 提交于 2019-12-10 13:15:44

问题


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.



来源:https://stackoverflow.com/questions/2025763/command-binding-memory-leak-in-wpf

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!