<p>I find that the .NET event model is such that I'll often be raising an event on one thread and listening for it on another thread.  I was wondering what the cleanest way to marshal an event from a background thread onto my UI thread is.</p>

<p>Based on the community suggestions, I've used this:</p>

<pre><code>// earlier in the code
mCoolObject.CoolEvent+= 
           new CoolObjectEventHandler(mCoolObject_CoolEvent);
// then
private void mCoolObject_CoolEvent(object sender, CoolObjectEventArgs args)
{
    if (InvokeRequired)
    {
        CoolObjectEventHandler cb =
            new CoolObjectEventHandler(
                mCoolObject_CoolEvent);
        Invoke(cb, new object[] { sender, args });
        return;
    }
    // do the dirty work of my method here
}
</code></pre>

[{'answer_id': 22387, 'author': 'Konrad Rudolph', 'author_id': 1968, 'author_profile': 'https://Stackoverflow.com/users/1968', 'pm_score': 4, 'selected': False, 'text': "<p>I shun redundant delegate declarations.</p>\n\n<pre><code>private void mCoolObject_CoolEvent(object sender, CoolObjectEventArgs args)\n{\n    if (InvokeRequired)\n    {\n        Invoke(new Action&lt;object, CoolObjectEventArgs&gt;(mCoolObject_CoolEvent), sender, args);\n        return;\n    }\n    // do the dirty work of my method here\n}\n</code></pre>\n\n<p>For non-events, you can use the <code>System.Windows.Forms.MethodInvoker</code> delegate or <code>System.Action</code>.</p>\n\n<p>EDIT: Additionally, every event has a corresponding <code>EventHandler</code> delegate so there's no need at all to redeclare one.</p>\n"}, {'answer_id': 22395, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': 2, 'selected': False, 'text': "<p>I've always wondered how costly it is to <em>always</em> assume that invoke is required...</p>\n\n<pre><code>private void OnCoolEvent(CoolObjectEventArgs e)\n{\n  BeginInvoke((o,e) =&gt; /*do work here*/,this, e);\n}\n</code></pre>\n"}, {'answer_id': 22397, 'author': 'Shaun Austin', 'author_id': 1120, 'author_profile': 'https://Stackoverflow.com/users/1120', 'pm_score': 6, 'selected': True, 'text': '<p>A couple of observations:</p>\n\n<ul>\n<li>Don\'t create simple delegates explicitly in code like that unless you\'re pre-2.0 so you could use: </li>\n</ul>\n\n<pre class="lang-cs prettyprint-override"><code>   BeginInvoke(new EventHandler&lt;CoolObjectEventArgs&gt;(mCoolObject_CoolEvent), \n               sender, \n               args);\n</code></pre>\n\n<ul>\n<li><p>Also you don\'t need to create and populate the object array because the args parameter is a "params" type so you can just pass in the list.</p></li>\n<li><p>I would probably favor <code>Invoke</code> over <code>BeginInvoke</code> as the latter will result in the code being called asynchronously which may or may not be what you\'re after but would make handling subsequent exceptions difficult to propagate without a call to <code>EndInvoke</code>. What would happen is that your app will end up getting a <code>TargetInvocationException</code> instead.</p></li>\n</ul>\n'}, {'answer_id': 22415, 'author': 'On Freund', 'author_id': 2150, 'author_profile': 'https://Stackoverflow.com/users/2150', 'pm_score': 0, 'selected': False, 'text': '<p>You can try to develop some sort of a generic component that accepts a <a href="http://msdn.microsoft.com/en-us/library/system.threading.synchronizationcontext.aspx" rel="nofollow noreferrer">SynchronizationContext</a> as input and uses it to invoke the events.</p>\n'}, {'answer_id': 22470, 'author': 'gbc', 'author_id': 1667, 'author_profile': 'https://Stackoverflow.com/users/1667', 'pm_score': 2, 'selected': False, 'text': '<p>As an interesting side note, WPF\'s binding handles marshaling automatically so you can bind the UI to object properties that are modified on background threads without having to do anything special.  This has proven to be a great timesaver for me.</p>\n\n<p>In XAML:</p>\n\n<pre><code>&lt;TextBox Text="{Binding Path=Name}"/&gt;\n</code></pre>\n'}, {'answer_id': 258385, 'author': 'Domenic', 'author_id': 3191, 'author_profile': 'https://Stackoverflow.com/users/3191', 'pm_score': 6, 'selected': False, 'text': '<p>I have <a href="https://github.com/domenic/extensions/blob/master/WindowsFormsInvokingExtensions.cs" rel="noreferrer">some code for this</a> online. It\'s much nicer than the other suggestions; definitely check it out.</p>\n\n<p>Sample usage:</p>\n\n<pre><code>private void mCoolObject_CoolEvent(object sender, CoolObjectEventArgs args)\n{\n    // You could use "() =&gt;" in place of "delegate"; it\'s a style choice.\n    this.Invoke(delegate\n    {\n        // Do the dirty work of my method here.\n    });\n}\n</code></pre>\n'}, {'answer_id': 803445, 'author': 'Dmitri Nesteruk', 'author_id': 9476, 'author_profile': 'https://Stackoverflow.com/users/9476', 'pm_score': 2, 'selected': False, 'text': '<p>I think the cleanest way is <strong>definitely</strong> to go the AOP route. Make a few aspects, add the necessary attributes, and you never have to check thread affinity again.</p>\n'}, {'answer_id': 12743503, 'author': 'TarPista', 'author_id': 1722587, 'author_profile': 'https://Stackoverflow.com/users/1722587', 'pm_score': 3, 'selected': False, 'text': '<p>I made the following \'universal\' cross thread call class for my own purpose, but I think it\'s worth to share it:</p>\n\n<pre><code>using System;\nusing System.Collections.Generic;\nusing System.Text;\nusing System.Windows.Forms;\n\nnamespace CrossThreadCalls\n{\n  public static class clsCrossThreadCalls\n  {\n    private delegate void SetAnyPropertyCallBack(Control c, string Property, object Value);\n    public static void SetAnyProperty(Control c, string Property, object Value)\n    {\n      if (c.GetType().GetProperty(Property) != null)\n      {\n        //The given property exists\n        if (c.InvokeRequired)\n        {\n          SetAnyPropertyCallBack d = new SetAnyPropertyCallBack(SetAnyProperty);\n          c.BeginInvoke(d, c, Property, Value);\n        }\n        else\n        {\n          c.GetType().GetProperty(Property).SetValue(c, Value, null);\n        }\n      }\n    }\n\n    private delegate void SetTextPropertyCallBack(Control c, string Value);\n    public static void SetTextProperty(Control c, string Value)\n    {\n      if (c.InvokeRequired)\n      {\n        SetTextPropertyCallBack d = new SetTextPropertyCallBack(SetTextProperty);\n        c.BeginInvoke(d, c, Value);\n      }\n      else\n      {\n        c.Text = Value;\n      }\n    }\n  }\n</code></pre>\n\n<p>And you can simply use SetAnyProperty() from another thread:</p>\n\n<pre><code>CrossThreadCalls.clsCrossThreadCalls.SetAnyProperty(lb_Speed, "Text", KvaserCanReader.GetSpeed.ToString());\n</code></pre>\n\n<p>In this example the above KvaserCanReader class runs its own thread and makes a call to set the text property of the lb_Speed label on the main form.</p>\n'}, {'answer_id': 31263315, 'author': 'The Lonely Coder', 'author_id': 1201038, 'author_profile': 'https://Stackoverflow.com/users/1201038', 'pm_score': 2, 'selected': False, 'text': '<p>Use the synchronisation context if you want to send a result to the UI thread. I needed to change the thread priority so I changed from using thread pool threads (commented out code) and created a new thread of my own. I was still able to use the synchronisation context to return whether the database cancel succeeded or not.</p>\n\n<pre><code>    #region SyncContextCancel\n\n    private SynchronizationContext _syncContextCancel;\n\n    /// &lt;summary&gt;\n    /// Gets the synchronization context used for UI-related operations.\n    /// &lt;/summary&gt;\n    /// &lt;value&gt;The synchronization context.&lt;/value&gt;\n    protected SynchronizationContext SyncContextCancel\n    {\n        get { return _syncContextCancel; }\n    }\n\n    #endregion //SyncContextCancel\n\n    public void CancelCurrentDbCommand()\n    {\n        _syncContextCancel = SynchronizationContext.Current;\n\n        //ThreadPool.QueueUserWorkItem(CancelWork, null);\n\n        Thread worker = new Thread(new ThreadStart(CancelWork));\n        worker.Priority = ThreadPriority.Highest;\n        worker.Start();\n    }\n\n    SQLiteConnection _connection;\n    private void CancelWork()//object state\n    {\n        bool success = false;\n\n        try\n        {\n            if (_connection != null)\n            {\n                log.Debug("call cancel");\n                _connection.Cancel();\n                log.Debug("cancel complete");\n                _connection.Close();\n                log.Debug("close complete");\n                success = true;\n                log.Debug("long running query cancelled" + DateTime.Now.ToLongTimeString());\n            }\n        }\n        catch (Exception ex)\n        {\n            log.Error(ex.Message, ex);\n        }\n\n        SyncContextCancel.Send(CancelCompleted, new object[] { success });\n    }\n\n    public void CancelCompleted(object state)\n    {\n        object[] args = (object[])state;\n        bool success = (bool)args[0];\n\n        if (success)\n        {\n            log.Debug("long running query cancelled" + DateTime.Now.ToLongTimeString());\n\n        }\n    }\n</code></pre>\n'}, {'answer_id': 66629283, 'author': 'mahirgul', 'author_id': 2703120, 'author_profile': 'https://Stackoverflow.com/users/2703120', 'pm_score': -1, 'selected': False, 'text': '<p>I am using something like</p>\n<pre><code>Invoke((Action)(() =&gt;\n        {\n            //your code\n        }));\n</code></pre>\n'}]
['https://Stackoverflow.com/questions/22356', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1490/']