1

I understand that C# use garbage collector to manage all the managed resources, when an instance are no longer referenced, GC may collect them.

But my question is: is there any good practice to properly remove those references?

Let's say we bought a Zoo, in this zoo we have 1 tiger and 1 alarm

public class Zoo
{
    public static Action OpenZoo;
    public Tiger tiger1 = new Tiger();
}

Tiger subscribed to OpenZoo event and will make sound when zoo opens

public class Tiger
{
    public Tiger()
    {
        Zoo.OpenZoo += Meow;
    }
    private void Meow() { }
}

One day we want to get rid of the tiger, to my understanding we CANNOT simply do

tiger1 = null

we have to make the tiger to unsubscribe to the alarm first, then null the tiger1 and hope gc kicks in or call CG.collect.

Zoo.OpenZoo -= Meow;
tiger1 = null

in this example there it's not that hard, but imagine we have multiple object subscribe to multiple event, getting referenced by multiple objects etc.

what if this tiger1 subscribed to all the youtube channel in the world, if we need to get rid of this tiger, we have to unsubscribe all the youtube channel all over again? how can you so sure you didn't missed one?

So my question is:

Are there any better ways to manage such situation?

  • 3
    I'm not sure if the Tiger should have access to the zoo. Maybe it should be the other way round – Thomas Weller Jan 19 '19 at 16:34
  • Assuming you cannot change the design as proposed in the above comment, you probably want to use [`WeakReference`](https://learn.microsoft.com/en-us/dotnet/standard/garbage-collection/weak-references) – UnholySheep Jan 19 '19 at 17:03
  • If the class that needs to be removed uses resource and, possibly, subscribes to events, let it implement `IDisposable` and dispose of the managed objects it references and unwire the events when you `Dispose()` of it. A Tiger shouldn't be allowed to open the Zoo. – Jimi Jan 19 '19 at 18:04
  • Possible duplicate of [Do event handlers stop garbage collection from occurring?](https://stackoverflow.com/questions/298261/do-event-handlers-stop-garbage-collection-from-occurring) – GSerg Jan 22 '19 at 14:18

0 Answers0