简体   繁体   English

使用弱引用字典跟踪 c# GC 对象(以避免 memory 泄漏)是个好主意吗?

[英]Is keeping track of c# GC objects (to avoid memory leaks) with a weak reference dictionary a good idea?

I have implemented a static class with a dictionary that tracks some objects in my application using weak references.我已经实现了一个 static class 和一个字典,该字典使用弱引用跟踪我的应用程序中的一些对象。

static Dictionary<Type,List<WeakReference>> Monitor;

On request (not in production) the garbage collector is forced and the dictionary is returned.根据请求(不在生产中)强制垃圾收集器并返回字典。 By checking the number of "Alive" objects for each type, I can quickly check if I have a memory leak because the number of alive objects is higher than expected.通过检查每种类型的“活动”对象的数量,我可以快速检查是否存在 memory 泄漏,因为活动对象的数量高于预期。 Given the simplicity and usefulness of this class made by me, I was wondering if there is something better in the dot net framework to keep track of certain objects, let's call them "observable".鉴于我制作的 class 的简单性和实用性,我想知道点网框架中是否有更好的东西来跟踪某些对象,我们称它们为“可观察的”。

Each contribution is highly appreciated.每一项贡献都受到高度赞赏。

Assuming that you do not want to use a profiler, then your approach can work.假设您不想使用分析器,那么您的方法可以工作。 But be aware that your solution itself presents a memory leak as any object you add to it will have a weakreference object present, even after the object has been collected.但请注意,您的解决方案本身会出现 memory 泄漏,因为您添加到其中的任何 object 都会存在弱引用 object,即使在收集了 ZA6268CFDE6931ACB49 之后也是如此。 You need to periodically remove the weakreferences that are no longer valid, one approach is to remove on add like shown here https://www.chriswirz.com/software/weak-reference-lists-in-c-sharp .您需要定期删除不再有效的弱引用,一种方法是在添加时删除,如下所示https://www.chriswirz.com/software/weak-reference-lists-in-c-sharp Also remember that you are not using a ConcurrentDictionary so you need to control access to that structure.还要记住,您没有使用 ConcurrentDictionary,因此您需要控制对该结构的访问。

If you are okay with spawning another process, you might have success in using the profiling api.如果您可以生成另一个进程,您可能会成功使用分析 api。 https://docs.microsoft.com/en-us/dotnet/framework/unmanaged-api/profiling/profiling-overview https://docs.microsoft.com/en-us/dotnet/framework/unmanaged-api/profiling/profiling-overview

You could spawn a process that attaches to the host, collects data and signals back with the results.您可以生成一个附加到主机的进程,收集数据并用结果返回信号。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM