Ryan Peschel
Ryan Peschel

Reputation: 11746

Is this a good idea for an extension method?

Often I see code like this scattered and duplicated around source code:

var handler = MyEvent;

if (handler != null)
{
    handler.Invoke(null, e);
}

Is there any reason not to just encapsulate it within an extension method like this?

public static void SafeInvoke<T>(this EventHandler<T> theEvent, object sender, T e) where T : EventArgs
{
    var handler = theEvent;

    if (handler != null)
    {
        handler.Invoke(sender, e);
    }
}

So that calls can just be made like so:

MyEvent.SafeInvoke(this, new MyEventArgs(myData));

Upvotes: 4

Views: 229

Answers (3)

Adam Ralph
Adam Ralph

Reputation: 29956

This is an interesting one. Jeffrey Richter talsk a lot about this in CLR via C#.

With a null check like the following:-

var handler = MyEvent;

if (handler != null)
{
    handler.Invoke(null, e);
}

The JIT compiler could potentially optimise away the handler variable entirely. However, the CLR team are aware that many developers use this pattern for raising events and have built this awareness into the JIT compiler. It is likely that this will remain in place in all future versions of the CLR because changing the behaviour might break too many existing applications.

There is no reason that you can't write an extension method to do this work for you (this is exactly what I have done). Note that the method itself may be JIT inlined (but the temporary variable still won't be optimised away).

If you envisage your application being used against another runtime, e.g. Mono (which I suspect mirrors the CLR's behaviour in this case anyway) or some other exotic runtime which may appear, then you can guard your code against the possibility of JIT inlining by adding [MethodImplAttribute(MethodImplOptions.NoInlining)] to your extension method.

If you decide not to use an extension method, another way to protect against JIT optimisation (which Jeffrey Richter recommends) is to assign the value to the temporary variable in a way which cannot be optimised away by the JIT compiler, e.g.

var handler = Interlocked.CompareExchange(ref MyEvent, null, null);

Upvotes: 3

cbp
cbp

Reputation: 25628

You are free to create such an extension method if the pattern bothers you.

The only downsides I can see is the added dependency on the namespace that your extension method class resides in, and the fact that other developers will need to waste 3 to 5 seconds of their lives working out what SafeInvoke does.

Upvotes: 0

Panos
Panos

Reputation: 991

Maybe because of Performance considerations.

Upvotes: 0

Related Questions