Skip to content

Instantly share code, notes, and snippets.

@kevingosse
Created September 22, 2022 10:27
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kevingosse/1298286d7e50c0979a4208703899a3ba to your computer and use it in GitHub Desktop.
Save kevingosse/1298286d7e50c0979a4208703899a3ba to your computer and use it in GitHub Desktop.
[MethodImpl(MethodImplOptions.AggressiveOptimization)]
static void Test()
{
var obj = new object();
// Run a garbage collection in 1 second
Task.Delay(1000).ContinueWith(_ => { GC.Collect(); });
// As soon as MyNativeMethod is called, there are no more references to obj
MyNativeMethod(new WeakReference(obj));
}
static void MyNativeMethod(WeakReference obj)
{
// The native method does not keep the object alive
// Doing stuff
Thread.Sleep(2000);
// Trying to use the object
Console.WriteLine("Is alive: " + obj.IsAlive); // Is alive: False
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment