Skip to content

Instantly share code, notes, and snippets.

@Joe4evr
Last active March 5, 2018 03:09
Show Gist options
  • Save Joe4evr/c51a73aa499c233fd32963dfcbaa49ff to your computer and use it in GitHub Desktop.
Save Joe4evr/c51a73aa499c233fd32963dfcbaa49ff to your computer and use it in GitHub Desktop.
using System;
using System.Runtime.CompilerServices;
internal sealed class Del
{
internal void Run() => _act();
private Action _act;
internal Action Act { set => _act = value; }
}
internal sealed class Ev
{
internal void Run() => Act();
internal event Action Act;
}
internal sealed class DelBack
{
[MethodImpl(MethodImplOptions.NoInlining | MethodImplOptions.NoOptimization)]
internal void Run() { }
}
internal sealed class EvBack
{
[MethodImpl(MethodImplOptions.NoInlining | MethodImplOptions.NoOptimization)]
internal void Run() { }
}
internal sealed class C
{
[MethodImpl(MethodImplOptions.NoInlining | MethodImplOptions.NoOptimization)]
void M() { }
private Del _d;
//ok
internal void TestD()
{
_d = new Del();
_d.Act = M;
_d.Run();
_d = null;
}
private Ev _e;
//ok
internal void TestE()
{
_e = new Ev();
_e.Act += M;
_e.Run();
_e = null;
}
private Action BackAct;
private DelBack _d2;
//somwhat ok...
//will keep the instance alive until
//the value of BackAct is replaced
//or this instance of C is GC'd
internal void TestDBack()
{
_d2 = new DelBack();
BackAct = _d2.Run;
BackAct();
_d2 = null;
}
private event Action BackEv;
private EvBack _e2;
//the problem case: will hold on to any instance that
//is used to subscribe to the event field here
//until this instance of C is GC'd
internal void TestEBack()
{
_e2 = new EvBack();
BackEv += _e2.Run;
BackEv();
_e2 = null;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment