C
C#4mo ago
kettlemug

Making a field eligible for GC

recently i've been working on a small game engine and i'm trying to call the GC to free my entities after i unload a world (i'm trying to trigger finalizers which will then make opengl resources eligible for disposal and then reclaimed through a seperate method) i was expecting for when i set my field _entities to null that it would become eligible for GC but the following code always shows the list is alive
// _entities is a List<T>
WeakReference listRef = new(_entities);
_entities = null!;

GC.Collect();
GC.WaitForPendingFinalizers();

Console.WriteLine($"list is alive? {listRef.IsAlive}");
// _entities is a List<T>
WeakReference listRef = new(_entities);
_entities = null!;

GC.Collect();
GC.WaitForPendingFinalizers();

Console.WriteLine($"list is alive? {listRef.IsAlive}");
how can i make _entities eligible to be GCed? (it's a private variable which is not ever passed to outside of the class)
3 Replies
Jimmacle
Jimmacle4mo ago
where is the normal dispose pattern failing you that you want to try and manhandle the GC?
kettlemug
kettlemug4mo ago
was just messing around seeing if i could avoid using a dispose method as much as possible, i don't like the ambiguity it causes especially when sharing something like a texture across multiple objects but if using it is easier than trying to control the gc then i might as well
br4kejet
br4kejet4mo ago
If it's anything like java then Collect is just a hint, it might not actually collect and it might not collect everything (it might decide to collect things in gen0, but _entities might be in gen1 or gen2 because it's a field) Maybe try create a new list with a million (boxed) long values, then sum them all and print to console (to ensure it won't get JIT'd out) That will probably result in a GC