CSharp · Console
using System;
using System.Runtime.CompilerServices;
public static class Program
{
public static class DelegateKeeper
{
private static ConditionalWeakTable<object, object> cwtAction = new ConditionalWeakTable<object, object>();
public static void KeepAlive(Action action) => cwtAction.Add(action.Target, new object());
}
public class SomeClass
{
public void DoSomething() { }
}
public static class GcHelper
{
public static void Collect()
{
// OK surely overkill but just to make sure. I will reduce it when everyting will be understood.
GC.Collect(GC.MaxGeneration, GCCollectionMode.Forced, true);
GC.WaitForPendingFinalizers();
GC.Collect(GC.MaxGeneration, GCCollectionMode.Forced, true);
GC.WaitForPendingFinalizers();
}
}
static SomeClass inst;
static WeakReference<Action> weakRef;
public static void Main()
{
Proc1Scoped();
GcHelper.Collect();
Console.WriteLine($"weakRef.Target is alive = {weakRef.TryGetTarget(out _)}, expected true because inst keep a hold on SomeClass.");
Proc2Scoped();
GcHelper.Collect();
Console.WriteLine($"weakRef.Target is alive = {weakRef.TryGetTarget(out _)}, expected false, because there is no more ref on SomeClass.");
}
private static void Proc1Scoped()
{
inst = new SomeClass();
var action = inst.DoSomething;
weakRef = new WeakReference<Action>(action);
DelegateKeeper.KeepAlive(action);
}
private static void Proc2Scoped()
{
inst = null;
}
}