开发者

How do you keep a list of objects in C# that does not interfere with garbage collection?

I'm trying to maintain a list of objects in a Manager class in C#. Basically a consumer class registers with the Manager class and the manager class maintains a collection of references to the consumer class. Now as far as my (limited) understanding of GC goes, keeping a reference to the consumer class will prevent the con开发者_C百科sumer class being garbage collected.

What I am after is a way of maintaining a reference to the class in the manager class that might or might not point to the consumer class (in a determinable way) depending on whether it has been garbage collected. How does one do this in c#?


You can use the WeakReference class to create a "weak" reference to an object. That is, the object will be a candidate for collection as long as it is only referenced by strong references.

If it's not referenced by strong references (only weak ones) then the garbage collector will consider it a candidate for garbage collection.


You're looking for weak references.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜