On the MSDN, I have found following:
public event EventHandler<MyEventArgs> SampleEvent;
public void DemoEvent(string val)
{
// Copy to a temporary variable to be thread-safe.
EventHandler<MyEventArgs> temp = SampleEvent;
Is it reference?
If so I do not understand its meaning as when SampleEvent became null, so does the temp
if (temp != null)
temp(this, new MyEventArgs(val));
}
This is a paranoia thing to do with threading. If another thread unsubscribes the last handler just after you’ve checked it for
null, it could becomenulland you’ll cause an exception. Since delegates are immutable, capturing a snapshot of the delegate into a variable stops this from happening.Of course, it does have the other side effect that you could (instead) end up raising the event against an object that thinks it already unsubscribed…
But to stress – this is only an issue when multiple threads are subscribing / unsubscribing to the object, which is a: rare, and b: not exactly desirable.