Threads, controls and generel confusion

Mar 17 2009 8:14 PM
Lets say I have this TreeView control which I want to fill from with nodes from a worker thread through a recursive method. I use the following, omitting the recursive method which actually calls the AddNode(TreeNode, TreeNode) method:
private delegate void AddNodeDelegate(TreeNode parent, TreeNode node);
private void AddNode(TreeNode parent, TreeNode node)
{
if (!treeView.InvokeRequired)
{
parent.Nodes.Add(node);
parent.Expand();
}
else
{
treeView.Invoke(new AddNodeDelegate(AddNode), new Object[] { parent, node });
}
}
Do I really need to create delegates and an accompanying method for every method I want to call on the TreeView from the worker thread? I mean, this quickly turns into a lot of boilerplate methods and delegates.

This is what I do at the moment but I certainly don’t like it but if that’s the way so be it but I could be missing something. What I mean is, is this the method to use when updating controls across threads?

Another question along these lines: Lets say I have this library, or want to create one, that contains one or more workerthreads and some events that gets raised by those threads. How do I safeguard the library, when writing it and/or using it, so its able to raise events where the eventhandlers may or may not end up updating a control? Checking the registered eventhandlers and checking if its a Control, which I once ended up doing if I remember correctly, doesn’t seem right?

I’m not that that new to C#/.NET but this threads/controls dilemma has hunted and confused me for long without me figuring out how to really handle it correctly and often I just end up avoiding threads altogether.
I do accept that I may be totally wrong on a lot of things, like the above, and that its finally time to figure these things out so Id appreciate any help. Googling and MSDN hasn’t really brought me much. Bear over with my poor linguistic skills and inability to express myself proper, English isn’t my native language (no shit ;) and all or much of this may not make much sense ;)