2011-04-22 19 views
2

ツリービューにツリービューを追加すると、UIがロックされません(フォームはドラッグで移動できます)。私はtheadを使用していますが、動作しません。この問題を解決する方法を教えてください。TreeNodeをツリービュースルースレッドに追加すると、UIがロックされる

using System; 
using System.Collections.Generic; 
using System.ComponentModel; 
using System.Data; 
using System.Drawing; 
using System.Text; 
using System.Windows.Forms; 
using System.Threading; 

namespace WindowsFormsApplication1 
{ 
public partial class Form1 : Form 
{ 

TreeView tree; 

TreeNode root; 
Button button; 

public Form1() 
{ 
this.Name = "Form1"; 
this.Text = "Form1"; 

root = new TreeNode("Hello"); 
tree = new TreeView(); 
tree.Location = new Point(0, 0); 
tree.Size = new Size(this.Width, this.Height - 70); 
tree.Anchor = AnchorStyles.Top | AnchorStyles.Bottom; 
this.Controls.Add(tree); 
tree.Nodes.Add(root); 

button = new Button(); 
button.Text = "Add nodes"; 
button.Location = new Point(0, this.Height - 70); 
button.Size = new Size(this.Width, 30); 
button.Anchor = AnchorStyles.Bottom; 
this.Controls.Add(button); 
button.Click += new EventHandler(button_Click); 
} 

void button_Click(object sender, EventArgs e) 
{ 
Thread t = new Thread(new ThreadStart(this.AddNode)); 
t.Start(); 
} 

void AddNode() 
{ 
if (this.tree.InvokeRequired) 
{ 
this.tree.BeginInvoke(new MethodInvoker(this.AddNodeInternal)); 
} 
else 
{ 
this.AddNodeInternal(); 
} 
} 

void AddNodeInternal() 
{ 

root.Collapse(); 
root.Nodes.Clear(); 

TreeNode[] nodesToAdd = new TreeNode[20000]; 
for (int i = 0; i < 20000; i++) 
{ 
System.Threading.Thread.Sleep(1); 
TreeNode node = new TreeNode("Node " + i.ToString()); 
nodesToAdd[i] = node; 
} 
root.Nodes.AddRange(nodesToAdd); 

root.Expand(); 
} 

delegate void AddNodeDelegate(); 
} 
} 

答えて

1

ツリーを更新する前にレイアウトを一時停止します。更新が完了したら、レイアウトを再開して変更を表示します。すなわち

tree.SuspendLayout(); 
// Do updates here 
tree.ResumeLayout(); 

更新がはるかに速くなり、UIが一見応答のままになりますこの方法です。

+1

しかし、この問題は解決しません! – dungnn07

関連する問題