Is NotifyPropertyChanged thread safe?

I look at NotifyPropertyChanged() from INotifyPropertyChanged and noticed that in the examples from Microsoft, for example here:

http://msdn.microsoft.com/en-us/library/system.componentmodel.inotifypropertychanged.aspx

At first, the delegate reference is not captured (as said here, for example: Using a zero check in an event handler )

I looked at the auto-generated Reference.cs for my services, and this check is done.

So my question is, should I do this (in any form, such as extension methods, etc.)? Are there any possible problems if I do not?

+4
source share
1 answer

You are correct, the verification must be performed, and their example is incorrect.

Below is the standard code.

 private void NotifyPropertyChanged(String propertyName) { var handler = PropertyChanged; if (handler != null) { handler (this, new PropertyChangedEventArgs(propertyName)); } } 

Edit: Further explanation of why this is necessary (and why it works)

In the MS example, they perform a null check directly in the PropertyChanged and then call it. Thus, the PropertyChanged property could become null between the null check and the call. By assigning a local variable to a delegate, we can guarantee that we will keep a reference to the delegate and that it cannot change between null checking and invocation.

+7
source

All Articles