I’ve seen many developers when wanting to invoke an Event they assign it to a local variable named handler and invoke handler instead of invoking Event directly.
Why we are not invoking Events directly?
private void OnSomethingChanged(EventArgs e)
{
if (SomethingEvent != null)
{
SomethingEvent(this, e);
}
}
The code you’ve posted isn’t thread-safe, basically. If the final subscriber unsubscribes in a different thread after the
ifcheck but before the invocation, you’ll get aNullReferenceException.One option is to write an extension method:
You can then write:
You’d probably want another overload for
EventHandler<T>, too.