Event Invocators in C #

When I implement an event in Visual Studio, Resharper is kind enough to suggest that I create an event invocator. I used to do this manually in the past, and my invocators always looked like this:

private void InvokePropertyChanged(PropertyChangedEventArgs e) { if (PropertyChanged != null) { PropertyChanged(this, e); } } 

but the creator created by Resharper looks like this (cleared a little manually)

  private void InvokePropertyChanged(PropertyChangedEventArgs e) { PropertyChangedEventHandler changed = PropertyChanged; if (changed != null) { changed(this, e); } } 

Do people in reactive brains know something about C #, am I not doing this? Is there any technical advantage to having a local variable, or is it just an artifact due to which they should automatically generate code?

+6
c # events
source share
3 answers

Yes. They know that the number of subscribers to an event can vary between "if" and an event handler call. They fix it in the local, where it no longer changes.

+8
source share

I think John Saunders may have a better answer.

For the record, I don’t even write "Invocators". I have extension methods that do this for me, and I just call PropertyChanged.Fire(this, "propName");

See this article for more details.

+5
source share

This is just a multithreading issue. This protects you in a multi-threaded environment.

For example, take this script:

 if (PropertyChanged != null) // PropertyChanged has one subscriber here { 

Now the second thread is unsubscribing here, changing the event handler ....

  PropertyChanged(this, e); // This is no longer valid! } 
+1
source share

All Articles