1

From this question (and others) there's this example of snapshoting the event handler value before invoking:

var tmp = _myEventHandler;
if(tmp != null) {
    tmp(sender, args);
}

However, if I pass in the event handler and args into a function does this do the same thing?

protected void Invoke(MyEventHandler handler, MyEventArgs args)
{
    if (handler != null)
        handler(this, args);
}

I would say yes, but after thinking about this I don't know if it is the same - like could an optimization process inline this function and remove the snapshot variable?

Community
  • 1
  • 1
E.Beach
  • 1,829
  • 2
  • 22
  • 34

2 Answers2

5

It indeed does the same thing. The code is simply checking that the event handler is non-null and hence available for raising. This code is no different for a field / parameter / local. The C# compiler or JITer cannot inline this in such a way that the temporary is removed because it would change the semantics of the program.

JaredPar
  • 733,204
  • 149
  • 1,241
  • 1,454
  • This is a good explanation. A parameter is just like a local variable. It has the same semantics. – usr Jan 22 '12 at 16:41
0

The race condition is explained in your other links, such as Marc Gravell's answer.

As @JaredPar points out, your code effectively does the same thing. However, it violates the standard event conventions for .NET, which recommend the following:

protected virtual void OnAlarmRaised(AlarmRaisedEventArgs e)

You are free to violate the pattern, but doing so goes against the grain for minimal (if any) benefit.

Community
  • 1
  • 1
TrueWill
  • 25,132
  • 10
  • 101
  • 150