異步加載樹節點

 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
相關文章
相關標籤/搜索