Raise Events in .NET on the main UI thread Raise Events in .NET on the main UI thread multithreading multithreading

Raise Events in .NET on the main UI thread


Your library could check the Target of each delegate in the event's invocation list, and marshal the call to the target thread if that target is ISynchronizeInvoke:

private void RaiseEventOnUIThread(Delegate theEvent, object[] args){  foreach (Delegate d in theEvent.GetInvocationList())  {    ISynchronizeInvoke syncer = d.Target as ISynchronizeInvoke;    if (syncer == null)    {      d.DynamicInvoke(args);    }    else    {      syncer.BeginInvoke(d, args);  // cleanup omitted    }  }}

Another approach, which makes the threading contract more explicit, is to require clients of your library to pass in an ISynchronizeInvoke or SynchronizationContext for the thread on which they want you to raise events. This gives users of your library a bit more visibility and control than the "secretly check the delegate target" approach.

In regard to your second question, I would place the thread marshalling stuff within your OnXxx or whatever API the user code calls that could result in an event being raised.


Here's itwolson's idea expressed as an extension method which is working great for me:

/// <summary>Extension methods for EventHandler-type delegates.</summary>public static class EventExtensions{    /// <summary>Raises the event (on the UI thread if available).</summary>    /// <param name="multicastDelegate">The event to raise.</param>    /// <param name="sender">The source of the event.</param>    /// <param name="e">An EventArgs that contains the event data.</param>    /// <returns>The return value of the event invocation or null if none.</returns>    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(new[] { sender, e });                }            }        }        return retVal;    }}

You then just raise your event like so:

MyEvent.Raise(this, EventArgs.Empty);


You can use the SynchronizationContext class to marshall calls to the UI thread in WinForms or WPF by using SynchronizationContext.Current.