static void Main(string[] args) { WeakReferences wr = createReferences(); YourObjectType o = null; wr.o.TryGetTarget(out o); //comment this line to collect it instead GC.Collect(); Action a = null; Console.WriteLine(wr.a.TryGetTarget(out a)); Console.WriteLine(wr.o.TryGetTarget(out o)); Console.ReadLine(); }
public static void Collect() { Interlocked.Exchange(ref _gcCount, 0); int collected = 0; int total = 0; foreach (var keyPair in WeakReferences) { if (keyPair.Value.Target == null) { WeakReference value; WeakReferences.TryRemove(keyPair.Key, out value); ++collected; } else { ++total; } } if (Tracer.TraceWarning) { Tracer.Warn("Collected " + collected + " weak references, total " + total); } }