I am using weak events when I can't deterministically unsubscribe (otherwise I would prefer +=
and -=
instead of weak event):
class SomeType
{
public SomeType(...)
{
// object doesn't know when it will be removed
WeakEventManager(SomeSource, EventArgs).AddHandler(someSourceInstance,
nameof(SomeSource.SomeEvent), (s, e) => { ... });
}
}
This way if object is garbage collected, then event handler will not be called. Perfect.
However. If object is not yet garbage collected (but there are no more strong references), then event handler will still be called.
My question is rather general: what should I do when using weak events? Should I expect invalid call in event handler when using weak events? Or should I force GC to avoid that case (kind of deterministic "clean up")? Something else?