欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

异步加载树节点

程序员文章站 2024-02-01 17:57:52
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 ......
 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