c# - why introduce a temp variable? -
this question has answer here:
- c# events , thread safety 15 answers
i saw lot of following usage of event handler. why assign handler local variable , use local variable?
event eventhandler propertychanged; private void raisepropertychanged(string propertyname) { var temp = propertychanged; if (temp != null) temp(this, new propertychangedeventargs(propertyname)); // why not "if (propertychanged != null) propertychanged(...)" }
the temporary variable ensures thread safety, because between check , actual call other thread may unsubscribe event result in nullreferenceexception
.
eric lippert has a great article on this
Comments
Post a Comment