Tony Tony - 2 months ago 17
C# Question

c# Event Creation: Raise vs invoke

Before C#6, i was using this routine to deal with generating events in a multi threaded program: (i found it somewhere, but can't remember where):

public static object Raise(this MulticastDelegate multicastDelegate, object sender, EventArgs e)
{
object retVal = null;

MulticastDelegate threadSafeMulticastDelegate = multicastDelegate;
if (threadSafeMulticastDelegate != null)
{
foreach (Delegate d in threadSafeMulticastDelegate.GetInvocationList())
{
var synchronizeInvoke = d.Target as ISynchronizeInvoke;
if ((synchronizeInvoke != null) && synchronizeInvoke.InvokeRequired)
retVal = synchronizeInvoke.EndInvoke(synchronizeInvoke.BeginInvoke(d, new[] { sender, e }));
else
retVal = d.DynamicInvoke(sender, e);
}
}
return retVal;
}


so all i had to do was Eventname.Raise(...,....)

now with C#6, i know the new was it using something like:
Eventname?.Invoke(...);

what i am wondering is, should i change all my event creations to Invoke as it works different to the Raise(), or is it the same thing ?

Answer

You should never have been using that method in the first place. It's way too complicated. Instead, something like this would have been better:

public static void Raise(this Delegate handler, object sender, EventArgs e)
{
    if (handler != null)
    {
        handler.DynamicInvoke(sender, e);
    }
}

As for whether you should change your event-raising code, I'd say no. Not unless you've got a lot of time to kill and like going through your entire code base replacing perfectly good code.

What you should do is fix your current Raise() method. And feel free for any new code to write it the new C# 6 way, i.e. MyEvent?.DynamicInvoke(this, EventArgs.Empty) (which effectively amounts to the exact same thing as MyEvent.Raise(this, EventArgs.Empty) using the above, except without the extra method call).

Comments