Daniel Vasquez Lopez

Wednesday, March 31, 2004

The action being performed on this control is being called from the wrong thread.

"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."
What does that Exception mean?
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.
You will need to use
delegates. The following code declares a delegate that is used to marshal the call to the main thread:

private delegate void GeneralDelegate(object state);
private GeneralDelegate invoker;
private void MethodRunningInMainThread(object state)
{
treeView1.Nodes.Add(new TreeNode((string)state));
}
private void EventHandlerRunningInOtherThread(object sender, System.EventArgs e)
{
invoker = new GeneralDelegate(MethodRunningInMainThread);
treeView1.Invoke(invoker, new object[]{"Some Text"});
}

Instead of using the TreeView control in the EventHandlerRunningInOtherThread 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 MethodRunningInMainThread method by the TreeView control.