ConditionalWeakTable - Prevents Memory Leaks
The ConditionalWeakTable<T, TData> prevents memory leaks by allowing garbage collection of keys when they are no longer referenced.
Before (Memory Leak Risk)
Without ConditionalWeakTable, extra data associated with an object keeps it in memory indefinitely.
class MyData { public string Data { get; set; } } class Program { static Dictionary<object, MyData> dict = new Dictionary<object, MyData>(); static void Main() { var key = new object(); dict[key] = new MyData { Data = "Some data" }; key = null; // The object is unreachable, but still held in `dict` GC.Collect(); Console.WriteLine(dict.Count); // Memory leak: `dict` still holds the object } }
After (Memory Leak Fixed)
Using ConditionalWeakTable, the associated data is automatically released when the key is garbage collected.
using System.Runtime.CompilerServices; class MyData { public string Data { get; set; } } class Program { static ConditionalWeakTable<object, MyData> table = new(); static void Main() { var key = new object(); table.Add(key, new MyData { Data = "Some data" }); key = null; // Now `key` can be garbage collected GC.Collect(); Console.WriteLine(table.Count); // Output: 0, no memory leak } }