Can you see downsides to this one-liner other than the fact that multiple uses of it would violate the DRY principle? It seems straightforward but the fact that I haven’t seen others propose it makes me wonder if there’s a downside to it.
This bit of code creates a WeakReference to a method and then registers an event handler that invokes the reference’s target.
SomeEvent += (sender, e) => ((Action)(new WeakReference((Action)ProcessEvent)).Target)();
Thanks,
Ben
I don’t think that pattern does what you expect. Are you trying to prevent the event from holding a reference to the current object so as to prevent memory leaks? The lambda expression will capture the value of
thisin order to evaluateProcessEvent(assumingProcessEventis an instance method), so you will still have the leak. This code is the same as doingSomeEvent += (sender, e) => ProcessEvent();.You may be trying to do something more like this (which also isn’t what you want):
Now the lambda expression will capture the WeakReference, so you won’t have a strong reference to
this. Unfortunately, nothing else is referencing the delegate created from ProcessEvent, so it will be removed on the next GC even ifthisis still alive. (This also doesn’t check for Target being null).You could try something like this:
and then use it like this:
That will keep a weak reference to the receiver of ProcessEvent, and will automatically remove the event handler from the event after it has been collected, which should prevent memory leaks as long as the event is raised regularly.