Treeview控件 - ContextSwitchDeadlock解决方法

时间:2010-01-25 21:39:31

标签: c# visual-studio-2008 treeview controls

我构建了一个树视图控件,列出了任何驱动器或文件夹的目录结构。但是,如果选择驱动器或具有大型文件夹和子文件夹结构的某些内容,则控件需要很长时间才能加载,并且在某些情况下会显示MDA ContextSwitchDeadlock消息。我已经禁用了MDA死锁错误消息并且它可以正常工作,但我不喜欢时间因素和应用程序看起来已经锁定。我如何修改代码以便它不断地传送消息,而不是缓冲整个视图并将其全部传递给控件,​​是否有一种方法可以将其推送到控件,因为它正在构建?

//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;
    }

谢谢R。

1 个答案:

答案 0 :(得分:4)

如果你不需要在TreeView中加载整个结构但只看到正在扩展的内容,你可以这样做:

// 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
    }
}

致电热线将是:

TreeNode root = new TreeNode(source_computer_fldbrowser.SelectedPath);
AddTopDirectories(root, source_computer_fldbrowser.SelectedPath);
treeView1.Nodes.Add(root);
相关问题