Treeview Control - ContextSwitchDeadlock workarounds

前端 未结 1 1508
不思量自难忘°
不思量自难忘° 2021-01-16 10:29

I have built a treeview control that lists the directory structure of any drive or folder. However, if you select a drive, or something with a large structure of folders an

相关标签:
1条回答
  • 2021-01-16 10:46

    If you not need the whole structure loaded in the TreeView but only see what is being expanded, you can do it this way:

    // Handle the BeforeExpand event
    private void treeView1_BeforeExpand(object sender, TreeViewCancelEventArgs e)
    {
       if (e.Node.Tag != null) {
           AddTopDirectories(e.Node, (string)e.Node.Tag);
       }
    }
    
    private void AddTopDirectories(TreeNode node, string path)
    {
        node.BeginUpdate(); // for best performance
        node.Nodes.Clear(); // clear dummy node if exists
    
        try {
            string[] subdirs = Directory.GetDirectories(path);
    
            foreach (string subdir in subdirs) {
                TreeNode child = new TreeNode(subdir);
                child.Tag = subdir; // save dir in tag
    
                // if have subdirs, add dummy node
                // to display the [+] allowing expansion
                if (Directory.GetDirectories(subdir).Length > 0) {
                    child.Nodes.Add(new TreeNode()); 
                }
                node.Nodes.Add(child);
            }
        } catch (UnauthorizedAccessException) { // ignore dir
        } finally {
            node.EndUpdate(); // need to be called because we called BeginUpdate
            node.Tag = null; // clear tag
        }
    }
    

    The call line will be:

    TreeNode root = new TreeNode(source_computer_fldbrowser.SelectedPath);
    AddTopDirectories(root, source_computer_fldbrowser.SelectedPath);
    treeView1.Nodes.Add(root);
    
    0 讨论(0)
提交回复
热议问题