views:

49

answers:

2

Hiya,

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 consumer 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#?

+5  A: 

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.

Dean Harding
Thanks. That's a pretty useful addition to the arsenal. Thanks people!
Stephen Ellis
+4  A: 

You're looking for weak references.

tzaman