gpt4 book ai didi

c# - 为什么这个线程方法需要 900 毫秒才能完成?

转载 作者:太空宇宙 更新时间:2023-11-03 17:13:56 26 4
gpt4 key购买 nike

private void Form1_Load(object sender, System.EventArgs e)
{
StartToFillTree();
}

private void StartToFillTree( )
{
try
{
tvFolders.Nodes.Clear();
tvFolders.Nodes.Add( new TreeNode("Loading", -1, -1) );

Thread explorerThread = new Thread( new ThreadStart( FillTreeInAnotherThread ) );
explorerThread.Start();
}
catch (Exception exc)
{
//Do the catch
}
}

private void FillTreeInAnotherThread()
{
try
{
CreateTree(this.tvFolders);
}
catch (Exception exc)
{
//Do the catch
}
}


public void ClearTreeview( TreeView tv )
{
tv.Nodes.Clear();
}

public void AddNodeToTreeview( TreeView tv, TreeNode node )
{
tv.Nodes.Add( node );
}

public void CreateTree(TreeView treeView)
{
try
{
TreeNode hoofdNode = new TreeNode( "NodeNam", 0, 0);
AddDrivesToHoofdNode(hoofdNode); //This method takes 1 ms

//This part takes 905 milliseconds if I can believe my profiler !!?? -----
if( treeView.InvokeRequired )
{
treeView.Invoke( new ClearTreeviewDelegate( this.ClearTreeview ), new object[] { treeView } );
treeView.Invoke( new AddNodeToTreeviewDelegate( this.AddNodeToTreeview ), new object[] { treeView, hoofdNode } );
}
else
{
treeView.Nodes.Clear();
treeView.Nodes.Add(hoofdNode);
}
//End of 900ms part ?? -----


AddFavorieteFolders(treeView);//This method takes 1 ms

}
catch (Exception ex)
{
//Do some catching
}
}

最佳答案

您不能在 UI 线程之外更新 UI 组件。所有这些 Invoke 调用都会将更新编码回 UI 线程,从而有效地再次序列化您的应用。

处理大型树的典型方法是仅在父节点展开时加载子节点,而不是在开始时尝试填充整棵树。

关于c# - 为什么这个线程方法需要 900 毫秒才能完成?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4069093/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com