简体   繁体   English

如何清理弱引用的集合?

[英]How to clean up a collection of weak references?

I have a collection that is filled with weak references to objects in an application. 我有一个集合,其中填充了对应用程序中对象的弱引用。 What is the best way to clean up the expired references of such collection. 清理此类集合的过期引用的最佳方法是什么。 Is it a good idea to have a timer object that periodically looks up dead references and removes them? 有一个定时器对象定期查找死引用并删除它们是一个好主意吗? Is there a better way to do this in C# .NET? 有没有更好的方法在C#.NET中执行此操作? EDIT: In my scenario the collection will be created once for the application, and will exists while the application is running, therefore will grow in size. 编辑:在我的场景中,该集合将为应用程序创建一次,并且在应用程序运行时将存在,因此将会增大。 It is important that its size be maintained. 保持其尺寸非常重要。

I'd prefer solutions for version 3.5 of the framework or earlier. 我更喜欢框架版本3.5或更早版本的解决方案。 Thanks. 谢谢。

Doing it in a timer might be overkill, and introduces concurrency issues to deal with. 在计时器中执行它可能会过度,并引入并发问题来处理。

What about just cleaning up dead references as part of some other operation? 如何清理死亡引用作为其他操作的一部分呢? For example, if it's a list and ordering isn't important then adding a new item could replace the first dead reference it finds with the new one instead of appending it to the end. 例如,如果它是一个列表并且排序并不重要,那么添加一个新项可以用新的一个替换它找到的第一个死引用而不是将它附加到结尾。 Or trigger a sweep whenever some event you don't expect to occur too frequently happens - perhaps when a lookup retrieves a dead reference. 或者,当您不希望发生过于频繁发生的事件时触发扫描 - 可能是在查找检索到死引用时。

You could start a thread that alternates between 你可以开始一个交替的线程

  • waiting for Full Garbage Collection to complete 等待完全垃圾收集完成
  • shedding the unwanted weakreferences. 摆脱不必要的弱点。

http://msdn.microsoft.com/en-us/library/system.gcnotificationstatus.aspx http://msdn.microsoft.com/en-us/library/system.gcnotificationstatus.aspx

As others have mentioned, you'll have to deal with concurrency issues with any approach that involves a separate thread. 正如其他人所提到的,你将不得不处理涉及单独线程的任何方法的并发问题。

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

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