TreeView and Threading...

  • Thread starter Thread starter eff_kay
  • Start date Start date
E

eff_kay

I am trying to add a node in System.Windows.Forms.TreeView
in another thread... I am doing this...

--
TreeNode temp = new TreeNode("Work Station " + (i + 1))
MainForm.TreeView.SelectedNode.Nodes.Add(temp);
--

But I get this exception...

--
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.
--

I have no idea how to work now... PLZ help...

Thanks
eff_kay
 
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.

this message is really self-explaining ;)
the problem with Windows' visual components is that you cannot modify visual
components from thread other that the one which created these components. it
does not work in Win32API and it does not work in .NET (however you get nice
exception message).

the problem should be resolved quite easily. you have to check whether you
are in the right thread and if not you should use .BeginInvoke or .Invoke.
here's how it works:

public delegate void VoidDelegate();

// form code, so this means 'current form'
if ( this.InvokeRequired == false )
{
// if we are in the thread that has created the form then we can
just call the method
MyMethod();
}
else
this.BeginInvoke( new VoidDelegate( MyMethod ) );

there are two things to remember:
1. if you need to call methods with different prototype, you should always
use correct delegate
(otherwise it will not even compile)
2. BeginInvoke invokes the method with the asynchronous call. if you do not
need it you can just use Invoke instead of BeginInvoke (it is more difficult
to collect the results if you use BeginInvoke but it does not stop the whole
program to wait for the method to complete).

Regards,
Wiktor Zychla
 
Back
Top