Pattern for implementing INotifyPropertyChanged?

后端 未结 3 1418
野趣味
野趣味 2021-02-09 07:32

I have seen the following pattern used for implementing INotifyPropertyChanged

private void NotifyPropertyChanged(string propertyName)
{
    PropertyChangedEvent         


        
相关标签:
3条回答
  • 2021-02-09 07:45

    In a multi-threaded world, the PropertyChanged may be set to null after the if statement has been evaluated.

    0 讨论(0)
  • 2021-02-09 07:58

    It's the thread safe method of raising events. By assigning the publicly accessible PropertyChanged event locally before using it you ensure that it won't be different between the 'if' statement and the line actually raising the event.

    0 讨论(0)
  • 2021-02-09 07:59

    Eric Lippert explains this in details in this blog article: Events and races.

    Basically, the idea is to avoid a race condition in case another thread unsubscribes the last handler for this event after you check PropertyChanged != null, but before you actually invoke PropertyChanged. If you make a local copy of the handler, this cannot happen (but you might end up calling a handler that's just been unsubscribed)

    0 讨论(0)
提交回复
热议问题