问题描述
一个快速的问题。说我有一个类,如下面的例子所示。 class Subscriber
{
private Publisher publisher =新发布者;
public Subscriber()
{
publisher.SomeEvent + = new EventHandler(OnEventFired);
}
private void OnEventFired(object sender,EventArgs e)
{
}
}
在程序的某个地方,我有一个如下所示的方法:
public void DoSomething()
{
订阅者订阅者=新订阅者();
}
我希望这会导致内存泄漏,因为订阅者从未取消订阅从出版商的事件,从而导致他们彼此保持强烈的参考?
这不会导致一个泄漏 - GC可以处理没有问题的循环引用。
但是,这意味着发布者将有效地引用订阅者,因此订阅者无法被垃圾收集,直到发布商有资格使用GC,或者取消订阅该事件。
A quick question. Say that I have a class implemented as in below example.
class Subscriber
{
private Publisher publisher = new Publisher;
public Subscriber()
{
publisher.SomeEvent += new EventHandler(OnEventFired);
}
private void OnEventFired(object sender, EventArgs e)
{
}
}
And somewhere in the program I have a method that looks like this:
public void DoSomething()
{
Subscriber subscriber = new Subscriber();
}
Am I right to expect that this would cause a memory leak since subscriber never unsubscribes from publishers event, thus resulting in them both maintaining strong reference to each other?
It wouldn't cause a leak - the GC can handle circular references with no problems.
However, it would mean that the publisher would effectively have a reference to the subscriber, so the subscriber couldn't be garbage collected until either the publisher is eligible for GC, or it unsubscribes from the event.
这篇关于垃圾收集器和事件处理程序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!