Using the BeginInvoke or async method to add node to treeview is too slow.

  • Thread starter Thread starter HeapOverFlow
  • Start date Start date
H

HeapOverFlow

Guest
Hello, I have a slow performance issue about begininvoke and async to access ui when i add tree nodes to treeview.

I use winform and i added many nodes to treeview.



rootTree = new TreeNode("First");
for (int i = 0; i < 3; i++)
{
TreeNode secondChild = new TreeNode("Second" + i);
for (int j = 0; j < 100; ++j)
{
TreeNode thirdChild = new TreeNode("Third" + j);
for (int k = 0; k < 3000; ++k)
{
TreeNode fourthChild = new TreeNode("Fourth" + i);

thirdChild.Nodes.Add(fourthChild);
}
secondChild.Nodes.Add(thirdChild);
}
rootTree.Nodes.Add(secondChild);
}

treeView1.Nodes.Add(rootTree);


I run this code in main thread which is in main form's constructor, and it is fast.

But in my real project, i have a worker thread which can networking, make tree nodes, merging tree nodes and so on.

This worker thread will request the server and the server will response to this worker thread(networking).

And then it will make tree nodes with responsed datum.

But i must use BeginInvoke() to add my tree nodes to treeview. (Only main thread can access to ui.)

Unfortunately there is too slow performance when i add the nodes to treeview.

It takes 30 seconds to add above nodes. (If i do not use begin invoke then, it takes under 0.0001 seconds)


And i tried async method instead of begin invoke.


public TreeNode GetTreeNode()
{
TreeNode rootTree = null;
rootTree = new TreeNode("First");

for (int i = 0; i < 3; i++)
{
TreeNode secondChild = new TreeNode("Second" + i);
for (int j = 0; j < 100; ++j)
{
TreeNode thirdChild = new TreeNode("Third" + j);
for (int k = 0; k < 3000; ++k)
{
TreeNode fourthChild = new TreeNode("Fourth" + i);
thirdChild.Nodes.Add(fourthChild);
}
secondChild.Nodes.Add(thirdChild);
}
rootTree.Nodes.Add(secondChild);
}
return rootTree;
}


public async void AddNodeToTreeView()
{
TreeNode node = null;
Task<TreeNode> task = Task<TreeNode>.Run(() => node =
GetTreeNode());
await task;

Console.WriteLine("Start");
Stopwatch watch = new Stopwatch();
watch.Start();
treeView1.Nodes.Add(node);
Console.WriteLine("End : " + watch.Elapsed.ToString());
}

And i called AddNodeToTreeView() in main thread. (Exactly i make test buttons and set click event to call AddNodeToTreeView())


The result elapsed time is 30 seconds.


Why does access(set, add, change) to ui by begin invoke and async method is slow? (If i use this in pure main thread without async then it is not slow)


How should i gonna do? May i get some solutions?

Continue reading...
 
Back
Top