我构建了一个 TreeView 控件,列出了任何驱动器或文件夹的目录结构。但是,如果您选择一个驱动器,或者具有大型文件夹和子文件夹结构的东西,则控件需要很长时间才能加载,并且在某些情况下会显示 MDA ContextSwitchDeadlock 消息。我已禁用 MDA 死锁错误消息并且它有效,但我不喜欢时间因素和应用程序看起来像已锁定。我如何修改代码以使其不断发送消息,而不是缓冲整个 View 并将其完整传递给控件,有没有办法在构建时将其推送到控件?
//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。
请您参考如下方法:
如果您不需要将整个结构加载到 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);
