未注册的事件处理程序导致内存泄漏

发布于 2024-07-12 09:41:26 字数 482 浏览 7 评论 0原文

我正在维护一个存在内存泄漏的网络应用程序。

根据我使用 Red Gate ANTS 内存分析器进行的调查,我非常确定内存泄漏是由业务层中的事件处理程序引起的。

有一个集合在添加的每个项目上注册一个事件处理程序,以便在项目的日期更改时该集合可以重新排序。 看来这个事件处理程序是罪魁祸首。

该应用程序的业务层非常复杂,因此将集合及其项目保留在内存中会拖拽一堆其他对象。

我已经在集合上实现了 IDisposable 并删除了 Dispose 方法中的事件处理程序:

p.OnPunchDateChanged -= this.OnPunchDateChanged;

但是,实现 IDisposable 没有帮助,因为我无法将所有对集合的引用包装在 using 或 try/catch 块中。 该集合由我无法控制的应用程序部分使用。

如何清除这些事件处理程序来解决此内存泄漏问题?

I'm maintaining a web application that has a memory leak.

Based on my investigation using Red Gate ANTS memory profiler I'm pretty sure that the memory leak is caused by event handlers in the business layer.

There's a collection that registers an event handler on each item that's added so that the collection can re-sort when the item's date is changed. It appears that this event handler is the culprit.

The business layer for this application is quite complicated, so keeping the collection and its items in memory drags a bunch of other objects with it.

I've implemented IDisposable on the collection and removed the event handlers in the Dispose method:

p.OnPunchDateChanged -= this.OnPunchDateChanged;

However, implementing IDisposable doesn't help since I can't wrap all the references to the collection in using or try/catch blocks. This collection is used by portions of the application that I don't have control over.

How can I clear these event handlers to resolve this memory leak?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

不再让梦枯萎 2024-07-19 09:41:27

首先,为了证明这一点,尝试将事件的添加和删除记录到一个简单的文本文件中。 然后,检查添加和删除的数量。

听起来好像业务逻辑中的某个地方存在错误,该错误不会在所有情况下取消注册事件。

First off, just to prove the point, try logging the adding and removal of events to a simple text file. Then, check how many were added vs removed.

It sounds as if there is a bug somewhere in the business logic which is not unregistering the event in all circumstances.

柠檬色的秋千 2024-07-19 09:41:27

集合上的 Dispose 方法应由您的代码直接调用,因为该事件保存对集合的引用。 您的收藏永远不会被垃圾收集器销毁。

您还应该更改集合的Remove 和Clean 方法的行为,以将事件处理程序与已删除的项目分离。

The Dispose method on the collection should be called directly by your code because the event holds a reference to the collection. Your collection will never be destroyed by garbage collector.

You should also change the behaviour of the Remove and Clean methods of the collection to detach the event handler from the removed items.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文