当添加TreeNode到TreeView线程时,UI被锁定
本文关键字:UI 锁定 线程 添加 TreeNode TreeView | 更新日期: 2023-09-27 17:51:21
我想当treenode添加到treeview时,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();
}
}
在开始更新树之前暂停布局。更新完成后,恢复布局,以便可以看到更改。例如
tree.SuspendLayout();
// Do updates here
tree.ResumeLayout();
这样更新将更快,UI将保持貌似响应。