I'm just starting to learn MVVM and WPF so sorry for asking stupid questions.
I'm using different tutorials and examples to learn and I come across this example (read Example 2) which I don't understand.
private void RaisePropertyChanged(string propertyName)
{
// take a copy to prevent thread issues
PropertyChangedEventHandler handler = PropertyChanged;
if (handler != null)
{
handler(this, new PropertyChangedEventArgs(propertyName));
}
}
Basically, the comment doesn't make much sense to me... "take a copy to prevent thread issues".
This line:
PropertyChangedEventHandler handler = PropertyChanged;
doesn't create a new, totally different handler
object (it's not cloned). It's just a new reference to the same PropertyChanged
object, right?
I did some tests to find out what is really happening:
PropertyChangedEventHandler handler = PropertyChanged;
var message = "PropertyChanged: " + PropertyChanged.GetHashCode() + "\n";
message += "handler: " + handler.GetHashCode() + "\n";
message += "are equal (1): " + (PropertyChanged.Equals(handler)) + "\n";
message += "are equal (2): " + (PropertyChanged == handler) + "\n";
MessageBox.Show(message);
Here's the result:
This confirms my theory that these 2 objects are really the SAME and the assignment is just a NOOP. What I don't understand is how is this related at all with "thread issues" (from the comment)?!?
And one more thing: after a bit of testing (using a really simple example) I found out that the PropertyChanged
event is never null. Why do we need the null check at all?
In my view the previous method can be condensed to just this:
private void RaisePropertyChanged(string propertyName)
{
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
I tested a bit (again, on a really simple example) and it seems to work very well... Is there some catch or something that I didn't find? Maybe I just found bad examples?
Anyway, there's a lot of stuff I don't know since as I said I just started learning WPF and MVVM, but I want to understand what is really happening, not just take some code and just paste it without understanding why and how it works. See cargo cult programming and magic programming.
EDIT
OK, based on the answers, the PropertyChanged
event can be changed between verification and call. More, the PropertyChanged
event can be null. However, I haven't been able to reproduce these behaviors...
Can someone actually give me an example where both statements happen? It would certainly help recognize similar situations.