开发者

UI has locked when add TreeNode to TreeView throught thread

I want when treenode is adding to treeview, the ui do not lock (Form can move by drag ...). I using thead, but it not work. Please tell me how or help me solve this problem.

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 Add开发者_JAVA技巧NodeInternal()
 {

 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();
 }
}


Suspend layout before starting to update the tree. After update is complete, resume the layout so that changes will be visible. i.e.

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

This way updates will be much much quicker and UI will remain seemingly responsive.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜