Threading ListBox and TreeView

  • Thread starter Thread starter Guest
  • Start date Start date
G

Guest

Hi Everybod

I can add some thing to ListBox from a new thread but can not add a node into a TreeView and get an exception that says you need marshaling. What is the difference and why

Thanks in advance for any reply
Tom
 
Hi Tom,

You shouldn't touch UI controls from within non UI thread.
Rather use Control.Invoke method.

--
Miha Markic [MVP C#] - RightHand .NET consulting & software development
miha at rthand com
www.rthand.com

Tom said:
Hi Everybody

I can add some thing to ListBox from a new thread but can not add a node
into a TreeView and get an exception that says you need marshaling. What is
the difference and why?
 
Hi Tom,

As Miha pointed out, Windows forms controls are inherently not
thread safe. So in effect, there may not be any guarantee that the
next time the list box is updated, it might succeed. In fact, we might
get the same marshalling error seen for the TreeView.
So if you mainpulate these controls from any thread
other then the main thread that owns the control,
it is safer to use Control.Invoke() to update the control.
For example:
To add an item to the ListBox from another thread:

delegate void AddToListBoxDelegate(String item);

// ...

if(listBox.InvokeRequired)
{
// Called from another thread ...
_listBox.Invoke(new AddToListBoxDelegate(Add,
new Object[] {"Hello"}));
}
else
{
_listBox.Items.Add("Hello");
}

// ...


public void Add(String item)
{
_listBox.Items.Add(item);
}

Regards,
Aravind C



Tom said:
Hi Everybody

I can add some thing to ListBox from a new thread but can not add a node
into a TreeView and get an exception that says you need marshaling. What is
the difference and why?
 
Back
Top