In one of the projects I take part in there is a vast use of WeakAction
. That\'s a class that allows to keep reference to an action instance without causing its tar
a.Target
provides access to the object which holds the lambda parameters. Performing a GetType
on this will return the compiler-generated type. One option would be to check this type for the custom attribute System.Runtime.CompilerServices.CompilerGeneratedAttribute
and keep a strong reference to the object in this case.
Now I can't change the way the WeakAction is called, (since it's in wide use) but I can change it's implementation.
Note that this is the only way so far which can keep it alive without requiring modifications to how the WeakAction
is constructed. It also doesn't attain the goal of keeping the lambda alive as long as the A
object (it would keep it alive as long as the WeakAction
instead). I do not believe that is going to be attainable without changing how the WeakAction
is constructed as is done in the other answers. At a minimum, the WeakAction
needs to obtain a reference to the A
object, which you currently do not provide.