Skip to content

Instantly share code, notes, and snippets.

@kevingosse
Created September 22, 2022 11:01
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/91db6426408f99119cbd0decdb35e9a2 to your computer and use it in GitHub Desktop.
Save kevingosse/91db6426408f99119cbd0decdb35e9a2 to your computer and use it in GitHub Desktop.
[MethodImpl(MethodImplOptions.AggressiveOptimization)]
static async Task AsyncMethod()
{
// Run a garbage collection in 1 second
Task.Delay(1000).ContinueWith(_ => { GC.Collect(); });
var taskCompletionSource = new TaskCompletionSource();
Action myDelegate = () => taskCompletionSource.SetResult();
MyNativeMethod(new WeakReference(myDelegate));
await taskCompletionSource.Task;
GC.KeepAlive(myDelegate);
}
static void MyNativeMethod(WeakReference myDelegate)
{
// Simulate an asynchronous operation
Task.Run(() =>
{
// Do some stuff
Thread.Sleep(2000);
Console.WriteLine("Is alive: " + myDelegate.IsAlive); // Is alive: False
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment