开发者

Treeview Control - ContextSwitchDeadlock workarounds

I have built a treeview control that lists the directory structure of开发者_如何学JAVA any drive or folder. However, if you select a drive, or something with a large structure of folders and sub folders the control takes a long time to load and in some instances shows an MDA ContextSwitchDeadlock message. I have disabled the MDA deadlock error message and it works, but I don't like the time factor and the app looking like it has locked. How can I modify the code so that it keeps pumping messages, and rather than buffering the whole view and passing it in its entirety to the control, is there a way of pushing it, to the control, as it is being built?

//Call line
treeView1.Nodes.Add(TraverseDirectory(source_computer_fldbrowser.SelectedPath));

private TreeNode TraverseDirectory(string path)
    {
        TreeNode result;
        try
        {
            string[] subdirs = Directory.GetDirectories(path);
            result = new TreeNode(path);
            foreach (string subdir in subdirs)
            {
                TreeNode child = TraverseDirectory(subdir);
                if (child != null) { result.Nodes.Add(child); }
            }
            return result;
        }
        catch (UnauthorizedAccessException)
        {
            // ignore dir
            result = null;
        }
        return result;
    }

Thanks R.


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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜