How my programs works
I have backend with several objects, which have PropetyChanged event. When some property is changed, the notification is fired. On the frontend side I have GUI written in WPF, and several properties are binded directly to WPF widgets.
To make GUI responsive, all the computation is done in additional thread.
So, in general, classic WPF app.
Error
public void OnPropertyChanged(string name)
{
if (PropertyChanged != null)
PropertyChanged(this, new PropertyChangedEventArgs(name)); // (*)
}
This code sends notifications, however it throws exception at (*) because PropertyChanged is null (yes, just after checking for null).
Question
My guess is it is because of rebinding in WPF — in my code I change the sender, so WPF has to unregister receiver and register it to the new sender. Exception is thrown rarely (I get one exception every ~40000 executions passes, each one is equivalent roughly to one change of the sender) but it does happen.
Now — how to properly lock PropertyChange, so I can check for null AND send the notification as an atomic operation? I don’t want to do this by trial & error, because I could find out side effects in every 1M-th execution.
There is a pattern to solve this problem: