异步加载树节点

 1 using System;
 2 using System.Collections.Generic;
 3 using System.ComponentModel;
 4 using System.Data;
 5 using System.Drawing;
 6 using System.Text;
 7 using System.Threading;
 8 using System.Windows.Forms;
 9 
10 namespace FormCallBackTest
11 {
12     public partial class Form1 : Form
13     {
14         //声明委托已实现回调机制 
15         private delegate void CallBackTest();
16         private CallBackTest callBackTest;
17 
18         public delegate void DelegateDone();//定义一个委托
19         public DelegateDone GetDelegateHandler; //声明委托
20 
21         public Form1()
22         {
23             InitializeComponent();
24 
25             //初始化回调
26             GetDelegateHandler = new DelegateDone(ThdFunc); //绑定需要回调的函数 
27         }
28         private void button1_Click(object sender, EventArgs e)
29         {
30             Thread th1 = new Thread(new ThreadStart(DoWork));//创建线程
31             th1.IsBackground = true;//后台线程
32             th1.Start();//启动线程 
33         }
34 
35         private void ThdFunc()
36         {
37             List<string> listTest = new List<string>();
38 
39             GetData(ref listTest);//获取数据
40             InitTreeInfo(listTest);//构建树节点
41         }
42         private void GetData(ref List<string> listTest)
43         {
44             listTest.Clear();
45             for (int i = 0; i < 1000000; i++)
46             {
47                 listTest.Add("测试数据" + i);
48             }
49         }
50         private void InitTreeInfo(List<string> listTest)
51         {
52             for (int i = 0; i < listTest.Count; i++)
53             {
54                 TreeNode SubNode = new TreeNode();
55                 SubNode.Name = Convert.ToString(i + 1);
56                 SubNode.Text = listTest[i];
57                 this.Invoke((MethodInvoker)delegate()
58                 {
59                     treeView1.Nodes.Add(SubNode);
60                 });//防止跨线程
61             }
62         }
63         void DoWork()
64         {
65             callBackTest = new CallBackTest(GetDelegateHandler);
66             CallBack(callBackTest);
67         }
68         //使用委托 
69         private void CallBack(CallBackTest Delegate)
70         {
71             Delegate();
72         }
73 
74     }
75 }
源码下载地址:https://files-cdn.cnblogs.com/files/yc1224/%E5%BC%82%E6%AD%A5%E5%8A%A0%E8%BD%BD%E6%A0%91%E8%8A%82%E7%82%B9.zip

 

posted @ 2019-12-12 14:52  ₯㎕~  阅读(...)  评论(...编辑  收藏