I have a situation where multiple classes are registering interest with another class to observe a certain property's value. This is being done by using delegates like so:
public delegate void ObservingHandler (object value);
Dictionary<ObservingHandler, ObservationInfo> _handlers = new Dictionary<ObservationHandler, ObservationInfo>();
public void register(ObservingHandler handler) {
// Observation info is created here and is just a struct
_handlers.Add(handler, info);
}
This works great and is really useful but currently when a registered object is released it has to tell the relevant class that it no longer wants to receive notifications. Otherwise I get NULL reference exceptions.
Currently this means I can't use lambda expressions because the observation handler is the key in the dictionary (and so needs to be the same instance when it comes to removing it).
What I would like to do is to check that each ObservationHandler
has a valid and instantiated class behind it before it is called. This way responsibility is taken away from the listening class.
Is there some way in Func
or delegate
to check the receiver of the function is alive and well?
EDIT:
The full source code comes from my project called SFCore on GitHub.