Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>I liked Mike Bouk's answer (+1) so much, I incorporated it into my codebase. I am concerned that his DynamicInvoke call will throw a runtime exception if the Delegate it invokes is not an EventHandler delegate, due to mismatched parameters. And since you're in a background thread, I assume you may want to call the UI method asynchronously and that you are not concerned with whether it ever finishes.</p> <p>My version below can only be used with EventHandler delegates and will ignore other delegates in its invocation list. Since EventHandler delegates return nothing, we don't need the result. This allows me to call EndInvoke after the asynchronous process completes by passing the EventHandler in the BeginInvoke call. The call will return this EventHandler in IAsyncResult.AsyncState by way of the AsynchronousCallback, at which point EventHandler.EndInvoke is called.</p> <pre><code>/// &lt;summary&gt; /// Safely raises any EventHandler event asynchronously. /// &lt;/summary&gt; /// &lt;param name="sender"&gt;The object raising the event (usually this).&lt;/param&gt; /// &lt;param name="e"&gt;The EventArgs for this event.&lt;/param&gt; public static void Raise(this MulticastDelegate thisEvent, object sender, EventArgs e) { EventHandler uiMethod; ISynchronizeInvoke target; AsyncCallback callback = new AsyncCallback(EndAsynchronousEvent); foreach (Delegate d in thisEvent.GetInvocationList()) { uiMethod = d as EventHandler; if (uiMethod != null) { target = d.Target as ISynchronizeInvoke; if (target != null) target.BeginInvoke(uiMethod, new[] { sender, e }); else uiMethod.BeginInvoke(sender, e, callback, uiMethod); } } } private static void EndAsynchronousEvent(IAsyncResult result) { ((EventHandler)result.AsyncState).EndInvoke(result); } </code></pre> <p>And the usage:</p> <pre><code>MyEventHandlerEvent.Raise(this, MyEventArgs); </code></pre>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload