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?