tag:blogger.com,1999:blog-6698224.post-1080786795636923432004-03-31T19:12:00.000-06:002004-08-11T10:05:29.516-05:00The action being performed on this control is being called from the wrong thread.<span style="font-size:85%;"><span style="font-family:trebuchet ms;"><span style="color:#000000;"><em>"The action being performed on this control is being called from the wrong thread. You must marshal to the correct thread using Control.Invoke or Control.BeginInvoke to perform this action."</em> <br /><strong>What does that Exception mean?</strong> <br />Window Forms Controls were not designed to be thread-safe. To be sure of that, check the member property Control.InvokeRequired of any control like the System.Windows.Forms.TreeView. If it is true, then you require to call the control from the thread where it was created by using Control.Invoke. <br />You will need to use </span></span></span><a href="http://msdn.microsoft.com/library/en-us/csref/html/vcrefTheDelegateType.asp"><span style="font-family:trebuchet ms;font-size:85%;color:#000000;">delegates</span></a><span style="color:#000000;"><span style="font-family:trebuchet ms;"><span style="font-size:85%;">. The following code declares a delegate that is used to marshal the call to the main thread: <br /></spam></span></span><span style="font-family:trebuchet ms;"><span style="font-size:85%;"></span></span></span> <br /><span style="font-family:trebuchet ms;"><span style="font-family:arial;font-size:85%;color:#000000;">private delegate void GeneralDelegate(object state); <br />private GeneralDelegate invoker; <br />private void MethodRunningInMainThread(object state) <br />{ <br /> treeView1.Nodes.Add(new TreeNode((string)state)); <br />} <br />private void EventHandlerRunningInOtherThread(object sender, System.EventArgs e) <br />{ <br /> invoker = new GeneralDelegate(MethodRunningInMainThread); <br /> treeView1.Invoke(invoker, new object[]{"Some Text"}); <br />} <br /></spam> <br /></span></span><span style="font-size:85%;"><span style="font-family:trebuchet ms;"><span style="color:#000000;">Instead of using the TreeView control in the <strong>EventHandlerRunningInOtherThread</strong> method, it creates a delegate (that could be created in the class contructor once) and calls the TreeView.Invoke method in order to marshal the values requiered ("Some Text") in the <strong>MethodRunningInMainThread</strong> method by the TreeView control. <br /></span> <br /></span></span><span style="font-size:85%;"><span style="font-family:trebuchet ms;"></spam></span></span>Danielhttp://www.blogger.com/profile/11219787932132490222noreply@blogger.com