Fredriku73
Fredriku73

Reputation: 3190

Garbage collector problem in C#

In C# code, I have three objects A, B and C. A and B each hold a reference to C. When A is destroyed I would like the reference from B to C to be deleted as well so that C can be destroyed by the Garbage Collector.

Is there a way to do this without deleting it manually from B? (The destructor in C is not called before the reference from B to C is deleted, so it is not effective here.)

Upvotes: 1

Views: 775

Answers (3)

GvS
GvS

Reputation: 52518

Solution 1

Is B referenced from anywhere else in you application?

If B is only accessable through A, then B and C will be "removed" when A is "removed".

Solution 2

You should send a signal to B when A is "removed". If B is known to A you can signal B from A. I would use an IDisposable pattern for this

Solution 3

Instead of directly referencing C from B, you can use a WeakReference from B to get to C.

Upvotes: 5

Vojislav Stojkovic
Vojislav Stojkovic

Reputation: 8153

It smells like a job for a WeakReference:

A weak reference allows the garbage collector to collect an object while still allowing an application to access the object. If you need the object, you can still obtain a strong reference to it and prevent it from being collected.

Sounds like you should refer from B to C via a WeakReference, instead of directly.

Upvotes: 10

Anton Gogolev
Anton Gogolev

Reputation: 115691

First off, define "remove". And then consider using WeakReference class.

Upvotes: 7

Related Questions