TreeView Management - ContextSwitchDeadlock Workarounds

I created a TreeView control that lists the directory structures of any drive or folder. However, if you select a drive or something with a large folder and subfolder structure, management takes a long time to load, and in some cases, an MDA ContextSwitchDeadlock message is displayed. I disabled the MDA deadlock error message and it works, but I don’t like the time factor and the application looks like it is blocked. How can I change the code so that it continues to pump messages, and instead of buffering the whole view and passing it entirely to the control, is there a way to click on the control when 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.

+1
source share
1 answer

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

 // 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); 
+4
source

Source: https://habr.com/ru/post/901066/


All Articles