how does PropertyChangedEventHandler work?

前端 未结 3 1375
一生所求
一生所求 2020-12-13 21:11

This is a really simple question, but I was wondering if someone could explain what the 4th line is actually doing? so the first line gives an event to the handler. I don\'t

3条回答
  •  醉梦人生
    2020-12-13 21:16

    If you just did:

    PropertyChanged(this, new PropertyChangedEventArgs(name))
    

    you would get a NullReferenceException if no one was subscribed to the event PropertyChanged. To counteract this you add a null check:

    if(PropertyChanged != null)
    {
        PropertyChanged(this, new PropertyChangedEventArgs(name))
    }
    

    Now, if you are using multi-threading someone could unsubscribe between the null check and the calling of the event, so you could still get a NullReferenceException. To handle that we copy the event handler to a temporary variable

      PropertyChangedEventHandler handler = PropertyChanged;
      if (handler != null)
      {
        handler(this, new PropertyChangedEventArgs(name));
      }
    

    Now if someone unsubscribes from the event our temporary variable handler will still point to the old function and this code now has no way of throwing a NullReferenceException.

    Most often you will see people use the keyword var instead, this makes it so you don't need to type in the full type of the temporary variable, this is the form you will see most often in code.

      var handler = PropertyChanged;
      if (handler != null)
      {
        handler(this, new PropertyChangedEventArgs(name));
      }
    

提交回复
热议问题