Created
February 16, 2021 18:40
-
-
Save pictos/974226514726e012529d1af014c877a4 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
namespace WeakTest | |
{ | |
class Program | |
{ | |
static WeakReference<SomeClass> myClass; | |
static SomeClass holder; | |
static void Main(string[] args) | |
{ | |
CreateClass(ref myClass); | |
Console.WriteLine("Hello World!"); | |
var target = GetTarget(ref myClass); | |
target.Tick += Target_Tick; | |
holder.TriggerTick(); | |
holder = null; | |
target = null; | |
GC.Collect(); | |
GC.WaitForPendingFinalizers(); | |
GC.Collect(); | |
GC.WaitForPendingFinalizers(); | |
GC.Collect(); | |
GC.WaitForPendingFinalizers(); | |
GC.Collect(); | |
GC.WaitForPendingFinalizers(); | |
var anotherTarget = GetTarget(ref myClass); | |
anotherTarget?.TriggerTick(); | |
if (anotherTarget is null) | |
Console.WriteLine("Disposed"); | |
} | |
private static void Target_Tick(object sender, EventArgs e) | |
{ | |
Console.WriteLine("Ticked"); | |
} | |
static SomeClass GetTarget(ref WeakReference<SomeClass> some) | |
{ | |
some.TryGetTarget(out var target); | |
return target; | |
} | |
static void CreateClass(ref WeakReference<SomeClass> weak) | |
{ | |
holder = new SomeClass(); | |
weak = new WeakReference<SomeClass>(holder); | |
} | |
} | |
class SomeClass | |
{ | |
public event EventHandler Tick; | |
public void TriggerTick() => Tick?.Invoke(this, EventArgs.Empty); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment