[英]Treeview Control - ContextSwitchDeadlock workarounds
我已經構建了一個treeview控件,列出了任何驅動器或文件夾的目錄結構。 但是,如果選擇驅動器或具有大型文件夾和子文件夾結構的某些內容,則控件需要很長時間才能加載,並且在某些情況下會顯示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.
如果您不需要在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);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.