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

标签 c# .net multithreading optimization

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/

相关文章:

c# - 嵌套使用是个好主意

c - gcc `__thread` 是如何工作的?

java - 客户端如何处理 "unable to create new native thread exception"

Python多线程内存占用高的问题

c# - 不支持 UWP NavigationView

c# - 资源管理器 7 上的大表性能不佳

.net - 通过合并两个配置文件来创建 System.Configuration.Configuration?

c# - iTextSharp 变音符号

c# - 使用 MvvmCross 从 Xamarin Android 中的 MvxListView 中删除项目

.net - Kubernetes pod 中的时间是几点?