gpt4 book ai didi

c# - 取消订阅类事件?

转载 作者:太空宇宙 更新时间:2023-11-03 21:20:49 26 4
gpt4 key购买 nike

我需要一些关于此类场景最佳实践的建议。我进行了搜索,但没有找到任何令人满意的答案。

我们在 winforms 项目中使用第 3 方 (.net) DLL。它引发了一些事件,我们订阅了。问题是,我是否需要在类里面明确取消订阅这些事件?

顺便说一句,我们都使用 .net framework 4。感谢您的建议。

一些示例代码...

public class MyClientCode: IDisposable
{
private readonly 3rdParty.TheirClass _theirClass;
public MyClientCode()
{
_theirClass = new _theirClass()
_theirClass.ReadData += ReadDataEvent;
}

public void SomeOtherMethod()
{
//some other code
}

public void ReadDataEvent()
{
//some code
}

public void Dispose()
{
_theirClass.ReadData -= ReadDataEvent;
}
}

在按钮点击事件中,我...

 MyClientCode code = new MyClientCode();
code.SomeOtherMethod();

最佳答案

如果不取消订阅,订阅该事件的对象将不会被垃圾回收(它会保留在内存中)。这会造成内存泄漏并导致内存使用过多。

但是,如果事件的生命周期与包含它的类的生命周期更短或相同,在您的情况下,内存将被正确收集。如果您有另一个对象引用非私有(private)事件,那么您将遇到问题。

参见 MSDN :

Until you unsubscribe from an event, the multicast delegate that underlies the event in the publishing object has a reference to the delegate that encapsulates the subscriber's event handler. As long as the publishing object holds that reference, your subscriber object will not be garbage collected.

请注意,如果您要退出应用程序,则无需取消订阅,除非它不应该保存在内存中。 (例如,当您关闭应用程序中的一个窗口时,您应该取消订阅任何事件,否则该窗口仍将保留在内存中。)如果手动销毁包含对象,则事件将也被销毁。

关于c# - 取消订阅类事件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30905250/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com