Here is a threaded version of your code:
private void AddNode(XmlNode inXmlNode, TreeNode inTreeNode)
{
TreeNode tNode ;
XmlNodeList nodeList ;
int i = 0;
if (inXmlNode.HasChildNodes)
{
nodeList = inXmlNode.ChildNodes;
List<manualresetevent> resetEvents = new List<manualresetevent>();
foreach (XmlNode XNode in nodeList)
{
tNode = new TreeNode(XNode.Name);
inTreeNode.Nodes.Add(tNode);
ManualResetEvent resetEvent = new ManualResetEvent(false);
resetEvents.Add(resetEvent);
ThreadPool.QueueUserWorkItem(state =>
{
AddNode(XNode, tNode);
resetEvent.Set();
});
}
WaitHandle.WaitAll(resetEvents.ToArray());
}
else
{
inTreeNode.Text = inXmlNode.InnerText.ToString();
}
}
EDIT: OP has implemented the code and hit the Thread Invoke Member error:
Update:
Well, here we get into a big ol' chat about Threads and how they work. This is a great subject to research because it is so useful and often used.
Basically, you have your code-behind running in one thread and your form running in a child thread (bet you didn't know that, did you ^_^).
The parent thread (code behind) can see it's own children, but the children can't see each other. Your inTreeNode does not exist in the recursive thread tree.
There are a couple of ways around this. The advice the error is giving you is to set up a method on the parent thread (code behind) that calls (invokes) the child thread running the form. You can call the parent thread from the child so the thread delegate can be used to access the form control.
With me so far? Perhaps not. If you use this method then you have to worry about "thread safety" which is preventing two threads trying to access the same object at the same time. It's the 'best' method but probably the most confusing.
Instead, the easier option is to pass the control as a parameter down to the recursive threads.
Change each AddNode to CreateNode that returns a TreeNode. Have each CreateNode method return the tNode object after it has called CreateNode and added the created nodes to tNode. After all recursions are complete you will be left with a brand new TreeNode in your parent thread. Then just add it to the TreeView ^_^
I will include the following example as is. I won't test it and I'm sure it won't work well. I'll leave that for you to fix as it is you who will be maintaining the code.
private TreeNode CreateNode(XmlNode xmlNode)
{
TreeNode treeNode = new TreeNode();
if (xmlNode.HasChildNodes)
{
List<ManualResetEvent> resetEvents = new List<ManualResetEvent>();
foreach (XmlNode xNode in xmlNode.ChildNodes)
{
ManualResetEvent resetEvent = new ManualResetEvent(false);
resetEvents.Add(resetEvent);
var node = xNode;
ThreadPool.QueueUserWorkItem(state =>
{
treeNode.Nodes.Add(CreateNode(node));
resetEvent.Set();
});
}
WaitHandle.WaitAll(resetEvents.ToArray());
}
else
{
treeNode.Text = xmlNode.InnerText;
}
return treeNode;
}