C#: Initializing an event handler with a dummy C#: Initializing an event handler with a dummy multithreading multithreading

C#: Initializing an event handler with a dummy


While you don't need to do the nullity checks, if you really want to try to make the event thread-safe, you still need to fetch it in a lock:

protected void OnPropertyChanged(string propertyName){    PropertyChangedEventHandler handler;    lock (propertyChangedLock)    {        handler = propertyChanged;    }    handler(this, new PropertyChangedEventArgs(propertyName));}

Otherwise you may not be fetching the most recent value - if event handlers are being added in a different thread, you could theoretically raise events forever without ever calling the new handlers. In practice I believe you'll almost always get away without the lock, but in memory-model terms you should have some sort of fence.

Personally I recommend that you don't try to make the events thread-safe.


You can see it as an implementation of the NULL Object pattern.

It helps making your code more readable, since you do not need to do NULL - value checks.

The locks in your add / remove logic will have to remain, if they're necessary now. They have nothing to do with it. They're used to avoid race-conditions (but i don't know if they're necessary in your very situation)