简体   繁体   中英

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? 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. 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

As others have mentioned, you'll have to deal with concurrency issues with any approach that involves a separate thread.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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