Speed up the loading a list of strings to a Treeview
<p>Stackflow and C# newbie here!</p>

<p>I have some code below which loads a list of strings into a treeview control and it works well. The only problem is the speed. When the lists are large it takes time to load, which isn't a problem except it locks up the UI for a while. </p>

<p>So an example would be a list of strings like this (but much larger):</p>

<p>c:\drivers\test1.txt<br>
c:\drivers\test2.txt<br>
c:\drivers\folder\test1.txt<br>
c:\brother\tester\text1.zip<br>
c:\brother\another\text2.zip<br>
c:\data\company1\accounts.rar<br>
c:\data\company2\accounts.rar<br></p>

<p>The treeview splits the strings using the backslash marker and puts them neatly in a explorer view - this is good!.</p>

<p>tvRestore is the Treeview control in example.</p>

<pre><code>foreach (string path in lstKeys)
        {

            lastNode = null;
            subPathAgg = string.Empty;
            foreach (string subPath in path.Split(new string[] { "\\" }, StringSplitOptions.None))
            {
                foreach (string item in subPath.Split(new string[] { "\\" }, StringSplitOptions.None))
                {
                    if (item == "" || item == null)
                    {
                        continue;
                    }
                    subPathAgg += item + "\\";

                    TreeNode[] n = tvRestore.Nodes.Find(subPathAgg, true);

                    if (n.Length &gt; 0)
                    {
                        lastNode = n[0];

                        continue;
                    }
                    else
                    {
                        // lastNode = null;
                    }

                    TreeNode[] nodes = tvRestore.Nodes.Find(subPathAgg, true);
                    if (nodes.Length == 0)
                        if (lastNode == null)
                            lastNode = tvRestore.Nodes.Add(subPathAgg, item);
                        else
                            lastNode = lastNode.Nodes.Add(subPathAgg, item);
                    else
                        lastNode = nodes[0];
                }
            }
        }
</code></pre>

<p>The only problem is the speed. I tried to use Threads but the code exceptions because the control is on a different Thread. I believe I have to Invoke the Nodes.Add but I can't figure out how to do this.</p>

<p>Ideally the code will start to populate the treeview when the application starts although I don't want the app to lockup for 30-40 seconds or longer for larger lists. </p>

<p>What is the best way to speed this process up? </p>