Stephen Ellis
Stephen Ellis

Reputation: 2711

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

Upvotes: 0

Views: 308

Answers (2)

tzaman
tzaman

Reputation: 47820

You're looking for weak references.

Upvotes: 4

Dean Harding
Dean Harding

Reputation: 72668

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.

Upvotes: 5

Related Questions