Control.Invoke and TreeView

J

Jacob Anderson

Hello,

I have an MT application where one thread reads a file
and then subsequently creates TreeNode instances in a
TreeView. I get the familiar:

System.InvalidOperationException: 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.

exception when it attempts to run the following code:

view.Nodes.Add(node);

where view is my TreeView instance, and node is my new
TreeNode instance (created in a background thread).

Reading through the MSDN docs doesn't really give me any
insight on how to use Control.Invoke in this case. Does
anyone have any guidance in this case? I can't run it
all in the application thread since the file it reads is
VERY large.

Thanks

-- Jake
(e-mail address removed)
 
W

Wiktor Zychla

Reading through the MSDN docs doesn't really give me any
insight on how to use Control.Invoke in this case. Does

everytime you use threads that perform some UI operations, you have to check
if the action is performed from the correct thread. the rule is quite
general:

void UpdateSomething()
{
........
if ( this.InvokeRequired )
{
this.Invoke( ...ActionX... );
}
else
ActionX();
.......
}

The method UpdateSomething can then be called from any thread. in your case
the method could read any data from any place and then use a method (in the
example above I named it 'ActionX') to put the data into the TreeView.

Regards,
Wiktor
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top