WPF 中的命令绑定内存泄漏
当我创建一个具有到 RoutedUICommand 的 CommandBinding 的用户控件时,我担心会出现内存泄漏。
场景:
有一个 RoutedUICommand 作为 c 类中的静态,我在其中存储命令 在用户控件上实现 CommandBindings。 将用户控件添加到主窗体。 从主窗体中删除用户控件,并将对其的引用设置为 null。
命令绑定的 canExecute 继续触发。我没有对 UserControl 的引用,因此它被泄露了。并且在表单关闭后它会持续触发很长时间。 (我还没有看到它停止)如果我强制进行垃圾收集,它就会被收集(好吧,canExecute 停止触发)
我有一个测试 项目 说明了这一点。我在 canExecute 中有一个 Console.WriteLine,它打印出触发该方法的对象的哈希代码。它有一个用于添加新用户控件的按钮和一个用于删除它的按钮。
我不应该关心这个吗?如果强制的话,用户控件确实会被收集。这是否意味着它将在下次收集时收集?我注意到我们的应用程序性能下降,并且正在跟踪内存泄漏等。我们有包含大量 ui 元素的复杂表单,当从布局中删除时,它们会占用处理器和内存空间。 (我们使用了很多命令)我认为一旦从可视化树中删除某些内容,它就无法再接收路由事件。我缺少什么?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
根据我的理解,命令绑定使用类似于(但不相同)的 WeakEvent 模式。
基本上,持有 WeakReference。这将允许它在您的引用消失后继续工作,但不会阻止您的类在没有其他引用时被 GC 收集。
简而言之,别担心——它正在按照它应该的方式工作。
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.