This question is a continuation of the C # Events and Thread Safety question (I am not the author of this) and Eric Lippert Events and Racing related blog. There are other similar questions on SO, but none of them address this case, the general consensus is that as long as you unsubscribe, you are safe, but I do not believe that this is true all the time.
According to the discussion on the SO question and the blog, the template to be used looks something like this:
var ev = NotifyPropertyChanged; if (ev != null) ev(this, new PropertyChangedEventArgs("Foo"));
But what if the following situation arises:
1) I sign the listener:
mytype.NotifyPropertyChanged += Handler; // Handler is instance method in SomeObject class
2) I (or the runtime, due to visibility) dispose of SomeObject, which contains the listener and unsubscribes the listener at about the same time that the property is notified.
3) Although this is unlikely due to the very short period of time in which this can happen, it is theoretically possible that since ev saves an old subscriber that no longer exists, it will call the function on an object that no longer exists.
According to Eric Lippert, "event handlers must be reliable in the face of the challenge, even after the event has been canceled." But if the handler is not signed and located , it can no longer take care of the call. What is the right way to deal with this situation?
Wrap code from (1) in try-catch? Which exception should be caught? ObjectDisposedException seems likely, but not the only thing that can happen, I think.
Alex K
source share