问题描述
我只是来实现,通过阅读StackOverflow的一些问题和答案,在C#中使用 + =
添加事件处理(或我想,其他.NET语言)可引起常见的内存泄漏...
I just came to realize, by reading some questions and answers on StackOverflow, that adding event handlers using +=
in C# (or i guess, other .net languages) can cause common memory leaks...
我在我的应用程序中使用的事件处理程序是这样,在过去很多次,从来没有意识到,他们可以引起或导致内存泄漏。
I have used event handlers like this in the past many times, and never realized that they can cause, or have caused, memory leaks in my applications.
这是如何工作的(意思是,为什么这实际上会导致内存泄漏)?
我怎样才能解决这个问题?是使用 - =
到相同的事件处理程序不够
是否有常见的设计模式或类似这样的处理情况的最佳做法?
例如:?我怎么处理,有许多不同的线程的应用程序,使用许多不同的事件处理程序,以提高对用户界面的几个事件
How does this work (meaning, why does this actually cause a memory leak) ?
How can I fix this problem ? Is using -=
to the same event handler enough ?
Are there common design patterns or best practices for handling situations like this ?
Example : How am I supposed to handle an application that has many different threads, using many different event handlers to raise several events on the UI ?
高效有什么好看的,简单的方法来监测这个在已建成的大型应用程序?
Are there any good and simple ways to monitor this efficiently in an already built big application?
推荐答案
原因很简单解释一下:当一个事件处理程序订阅时,的发行事件的的保存到用户的通过事件处理程序委托(假设该委托是一个实例方法)。
The cause is simple to explain: while an event handler is subscribed, the publisher of the event holds a reference to the subscriber via the event handler delegate (assuming the delegate is an instance method).
如果发布者的生活比订户长,则它将保持订户活,即使有向订户任何其它引用
If the publisher lives longer than the subscriber, then it will keep the subscriber alive even when there are no other references to the subscriber.
如果您从事件退订用等处理程序,那么,这将删除处理程序和可能的泄漏。然而,在我的经验,这是很少实际上是一个问题 - 因为通常我发现,发布者和用户都大致相等的寿命反正
If you unsubscribe from the event with an equal handler, then yes, that will remove the handler and the possible leak. However, in my experience this is rarely actually a problem - because typically I find that the publisher and subscriber have roughly equal lifetimes anyway.
它的是的一个可能的原因......但在我的经验,这是相当过分夸大。您的里程可能会有所不同,当然......你只需要小心。
It is a possible cause... but in my experience it's rather over-hyped. Your mileage may vary, of course... you just need to be careful.
这篇关于为什么以及如何避免事件处理程序内存泄漏?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!