<p>When you subscribe to an event on an object from within a form, you are essentially handing over control of your callback method to the event source. You have no idea whether that event source will choose to trigger the event on a different thread.</p>

<p>The problem is that when the callback is invoked, you cannot assume that you can make update controls on your form because sometimes those controls will throw an exception if the event callback was called on a thread different than the thread the form was run on.</p>

[{'answer_id': 6189, 'author': 'Simon Gillbee', 'author_id': 756, 'author_profile': 'https://Stackoverflow.com/users/756', 'pm_score': 4, 'selected': False, 'text': '<p>Here are the salient points:</p>\n\n<ol>\n<li>You can\'t make UI control calls from a different thread than the one they were created on (the form\'s thread).</li>\n<li>Delegate invocations (ie, event hooks) are triggered on the same thread as the object that is firing the event. </li>\n</ol>\n\n<p>So, if you have a separate "engine" thread doing some work and have some UI watching for state changes which can be reflected in the UI (such as a progress bar or whatever), you have a problem. The engine fire\'s an object changed event which has been hooked by the Form. But the callback delegate that the Form registered with the engine gets called on the engine\'s thread… not on the Form\'s thread. And so you can\'t update any controls from that callback. Doh!</p>\n\n<p><strong>BeginInvoke</strong> comes to the rescue. Just use this simple coding model in all your callback methods and you can be sure that things are going to be okay:</p>\n\n<pre><code>private delegate void EventArgsDelegate(object sender, EventArgs ea);\n\nvoid SomethingHappened(object sender, EventArgs ea)\n{\n   //\n   // Make sure this callback is on the correct thread\n   //\n   if (this.InvokeRequired)\n   {\n      this.Invoke(new EventArgsDelegate(SomethingHappened), new object[] { sender, ea });\n      return;\n   }\n\n   //\n   // Do something with the event such as update a control\n   //\n   textBox1.Text = "Something happened";\n}\n</code></pre>\n\n<p>It\'s quite simple really.</p>\n\n<ol>\n<li>Use <strong>InvokeRequired</strong> to find out if this callback happened on the correct thread.</li>\n<li>If not, then reinvoke the callback on the correct thread with the same parameters. You can reinvoke a method by using the <strong>Invoke</strong> (blocking) or <strong>BeginInvoke</strong> (non-blocking) methods.</li>\n<li>The next time the function is called, <strong>InvokeRequired</strong> returns false because we are now on the correct thread and everybody is happy. </li>\n</ol>\n\n<p>This is a very compact way of addressing this problem and making your Forms safe from multi-threaded event callbacks.</p>\n'}, {'answer_id': 6197, 'author': 'Chris Farmer', 'author_id': 404, 'author_profile': 'https://Stackoverflow.com/users/404', 'pm_score': 0, 'selected': False, 'text': '<p>In many simple cases, you can use the MethodInvoker delegate and avoid the need to create your own delegate type.</p>\n'}, {'answer_id': 6211, 'author': 'Jake Pearson', 'author_id': 632, 'author_profile': 'https://Stackoverflow.com/users/632', 'pm_score': 6, 'selected': True, 'text': '<p>To simplify Simon\'s code a bit, you could use the built in generic Action delegate.  It saves peppering your code with a bunch of delegate types you don\'t really need.  Also, in .NET 3.5 they added a params parameter to the Invoke method so you don\'t have to define a temporary array.</p>\n\n<pre><code>void SomethingHappened(object sender, EventArgs ea)\n{\n   if (InvokeRequired)\n   {\n      Invoke(new Action&lt;object, EventArgs&gt;(SomethingHappened), sender, ea);\n      return;\n   }\n\n   textBox1.Text = "Something happened";\n}\n</code></pre>\n'}, {'answer_id': 37136, 'author': 'Jason Diller', 'author_id': 2187, 'author_profile': 'https://Stackoverflow.com/users/2187', 'pm_score': 3, 'selected': False, 'text': '<p>I use anonymous methods a lot in this scenario: </p>\n\n<pre><code>void SomethingHappened(object sender, EventArgs ea)\n{\n   MethodInvoker del = delegate{ textBox1.Text = "Something happened"; }; \n   InvokeRequired ? Invoke( del ) : del(); \n}\n</code></pre>\n'}, {'answer_id': 341879, 'author': 'OwenP', 'author_id': 2547, 'author_profile': 'https://Stackoverflow.com/users/2547', 'pm_score': 2, 'selected': False, 'text': '<p>I\'m a bit late to this topic, but you might want to take a look at the <a href="http://msdn.microsoft.com/en-us/library/wewwczdw.aspx" rel="nofollow noreferrer">Event-Based Asynchronous Pattern</a>.  When implemented properly, it guarantees that events are always raised from the UI thread.</p>\n\n<p>Here\'s a brief example that only allows one concurrent invocation; supporting multiple invocations/events requires a little bit more plumbing.</p>\n\n<pre><code>using System;\nusing System.ComponentModel;\nusing System.Threading;\nusing System.Windows.Forms;\n\nnamespace WindowsFormsApplication1\n{\n    public class MainForm : Form\n    {\n        private TypeWithAsync _type;\n\n        [STAThread()]\n        public static void Main()\n        {\n            Application.EnableVisualStyles();\n            Application.Run(new MainForm());\n        }\n\n        public MainForm()\n        {\n            _type = new TypeWithAsync();\n            _type.DoSomethingCompleted += DoSomethingCompleted;\n\n            var panel = new FlowLayoutPanel() { Dock = DockStyle.Fill };\n\n            var btn = new Button() { Text = "Synchronous" };\n            btn.Click += SyncClick;\n            panel.Controls.Add(btn);\n\n            btn = new Button { Text = "Asynchronous" };\n            btn.Click += AsyncClick;\n            panel.Controls.Add(btn);\n\n            Controls.Add(panel);\n        }\n\n        private void SyncClick(object sender, EventArgs e)\n        {\n            int value = _type.DoSomething();\n            MessageBox.Show(string.Format("DoSomething() returned {0}.", value));\n        }\n\n        private void AsyncClick(object sender, EventArgs e)\n        {\n            _type.DoSomethingAsync();\n        }\n\n        private void DoSomethingCompleted(object sender, DoSomethingCompletedEventArgs e)\n        {\n            MessageBox.Show(string.Format("DoSomethingAsync() returned {0}.", e.Value));\n        }\n    }\n\n    class TypeWithAsync\n    {\n        private AsyncOperation _operation;\n\n        // synchronous version of method\n        public int DoSomething()\n        {\n            Thread.Sleep(5000);\n            return 27;\n        }\n\n        // async version of method\n        public void DoSomethingAsync()\n        {\n            if (_operation != null)\n            {\n                throw new InvalidOperationException("An async operation is already running.");\n            }\n\n            _operation = AsyncOperationManager.CreateOperation(null);\n            ThreadPool.QueueUserWorkItem(DoSomethingAsyncCore);\n        }\n\n        // wrapper used by async method to call sync version of method, matches WaitCallback so it\n        // can be queued by the thread pool\n        private void DoSomethingAsyncCore(object state)\n        {\n            int returnValue = DoSomething();\n            var e = new DoSomethingCompletedEventArgs(returnValue);\n            _operation.PostOperationCompleted(RaiseDoSomethingCompleted, e);\n        }\n\n        // wrapper used so async method can raise the event; matches SendOrPostCallback\n        private void RaiseDoSomethingCompleted(object args)\n        {\n            OnDoSomethingCompleted((DoSomethingCompletedEventArgs)args);\n        }\n\n        private void OnDoSomethingCompleted(DoSomethingCompletedEventArgs e)\n        {\n            var handler = DoSomethingCompleted;\n\n            if (handler != null) { handler(this, e); }\n        }\n\n        public EventHandler&lt;DoSomethingCompletedEventArgs&gt; DoSomethingCompleted;\n    }\n\n    public class DoSomethingCompletedEventArgs : EventArgs\n    {\n        private int _value;\n\n        public DoSomethingCompletedEventArgs(int value)\n            : base()\n        {\n            _value = value;\n        }\n\n        public int Value\n        {\n            get { return _value; }\n        }\n    }\n}\n</code></pre>\n'}, {'answer_id': 10824842, 'author': 'Chase', 'author_id': 1234970, 'author_profile': 'https://Stackoverflow.com/users/1234970', 'pm_score': 2, 'selected': False, 'text': '<p>As the <code>lazy programmer</code>, I have a very lazy method of doing this.</p>\n\n<p>What I do is simply this.</p>\n\n<pre><code>private void DoInvoke(MethodInvoker del) {\n    if (InvokeRequired) {\n        Invoke(del);\n    } else {\n        del();\n    }\n}\n//example of how to call it\nprivate void tUpdateLabel(ToolStripStatusLabel lbl, String val) {\n    DoInvoke(delegate { lbl.Text = val; });\n}\n</code></pre>\n\n<p>You could inline the DoInvoke inside your function or hide it within separate function to do the dirty work for you.</p>\n\n<p>Just keep in mind you can pass functions directly into the DoInvoke method.</p>\n\n<pre><code>private void directPass() {\n    DoInvoke(this.directInvoke);\n}\nprivate void directInvoke() {\n    textLabel.Text = "Directly passed.";\n}\n</code></pre>\n'}]
['https://Stackoverflow.com/questions/6184', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/756/']