防止具有附加行为的内存泄漏 [英] Preventing Memory Leaks with Attached Behaviours

查看:86
本文介绍了防止具有附加行为的内存泄漏的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在WPF应用程序中创建了一个附加行为",使我可以处理Enter键并移至下一个控件.我将其称为EnterKeyTraversal.IsEnabled,您可以在我的博客

I've created an "attached behaviour" in my WPF application which lets me handle the Enter keypress and move to the next control. I call it EnterKeyTraversal.IsEnabled, and you can see the code on my blog here.

我现在主要担心的是我可能会发生内存泄漏,因为我正在处理UIElements上的PreviewKeyDown事件,而从不显式摘机"该事件.

My main concern now is that I may have a memory leak, since I'm handling the PreviewKeyDown event on UIElements and never explicitly "unhook" the event.

防止这种泄漏(如果确实存在)的最佳方法是什么?我是否应该保留要管理的元素的列表,并在Application.Exit事件中取消预告事件PreviewKeyDown?是否有人在自己的WPF应用程序中成功完成了附加行为,并提出了一种优雅的内存管理解决方案?

What's the best approach to prevent this leak (if indeed there is one)? Should I keep a list of the elements I'm managing, and unhook the PreviewKeyDown event in the Application.Exit event? Has anyone had success with attached behaviours in their own WPF applications and come up with an elegant memory-management solution?

推荐答案

我不同意DannySmurf

I do not agree DannySmurf

某些WPF布局对象可能会阻塞您的内存,并在不进行垃圾回收时使您的应用程序真正变慢.因此,我发现单词的选择是正确的,您正在将内存泄漏给不再使用的对象.您希望这些项目被垃圾回收,但它们不是垃圾回收,因为在某处有一个引用(在这种情况下,是事件处理程序中的引用).

Some WPF layout objects can clog up your memory and make your application really slow when they are not garbage collected. So I find the choice of words to be correct, you are leaking memory to objects you no longer use. You expect the items to be garbage collected, but they aren't, because there is a reference somewhere (in this case in the from an event handler).

现在是一个真正的答案:)

Now for a real answer :)

我建议您阅读此 MSDN上的WPF性能文章

不删除对象上的事件处理程序 可能使对象保持活动状态

Not Removing Event Handlers on Objects may Keep Objects Alive

对象传递给的委托 它的事件实际上是一个参考 那个对象.因此,事件 处理程序可以使对象存活的时间更长 比预期的要好.进行清洁时 已注册到的对象 听一个对象的事件,它是 删除该代表必不可少的 释放对象之前.保持 不需要的物体活着会增加 应用程序的内存使用情况.这是 当对象是 逻辑树或视觉对象的根 树.

The delegate that an object passes to its event is effectively a reference to that object. Therefore, event handlers can keep objects alive longer than expected. When performing clean up of an object that has registered to listen to an object's event, it is essential to remove that delegate before releasing the object. Keeping unneeded objects alive increases the application's memory usage. This is especially true when the object is the root of a logical tree or a visual tree.

他们建议您研究弱事件模式

另一种解决方案是在完成对象处理后删除事件处理程序.但是我知道,对于附加属性,这一点可能并不总是很清楚.

Another solution would be to remove the event handlers when you are done with an object. But I know that with Attached Properties that point might not always be clear..

希望这会有所帮助!

这篇关于防止具有附加行为的内存泄漏的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆