實現的功能是
1、按button2之後,label2會每100毫秒顯示一次數字,數字從0到99。(委託方式實現)
2、按button3之後,類比耗時操作5秒後label3顯示為目前時間。(BackgroundWorker方式實現)
3、在1、2執行的時候,按button1可以將label1的內容改為textbox1的內容。(此處為主線程式控制制,用於顯示多線程未死結主線程)
1 using System;
2 using System.Collections.Generic;
3 using System.ComponentModel;
4 using System.Data;
5 using System.Drawing;
6 using System.Linq;
7 using System.Text;
8 using System.Windows.Forms;
9 using System.Threading;
10
11 namespace WindowsFormsApplication1
12 {
13 public partial class Form1 : Form
14 {
15 private delegate void SetState(int x);//代理
16 public Form1()
17 {
18 InitializeComponent();
19 Thread.CurrentThread.Name = "Main";//主線程命名
20 Console.WriteLine(Thread.CurrentThread.Name);
21 }
22
23 private void TempFunction() //中轉函數,用來連續多次調用目標函數並類比延時
24 {
25 for (int i = 0; i < 100;i++ )
26 {
27 ThreadFunction(i);
28 Thread.Sleep(100);
29 }
30 }
31 private void ThreadFunction(int x) //實際控制項操作函數
32 {
33 if (label2.InvokeRequired) //用委託來操作
34 {
35 SetState ss = new SetState(ThreadFunction);
36 Invoke(ss,new object[]{x});
37 Console.WriteLine(Thread.CurrentThread.Name);
38 }
39 else //普通方式操作
40 {
41 label2.Text = x.ToString();
42 label2.Update();
43 Console.WriteLine(Thread.CurrentThread.Name);
44 }
45
46 }
47
48 private void button1_Click(object sender, EventArgs e) //主線程的按鈕操作,用來顯示區別所在
49 {
50 label1.Text = textBox1.Text;
51 }
52
53 private void button2_Click(object sender, EventArgs e) //按下按鈕後開始多線程操作
54 {
55 Thread th1 = new Thread(new ThreadStart(TempFunction));
56 th1.IsBackground = true;
57 th1.Name = "kidfruit";
58 th1.Start();
59 }
60
61 private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e) //使用BackgroundWorker控制項
62 {
63 Thread.Sleep(5000); //類比操作延時
64 }
65
66 private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e) //BackgroundWorker耗時操作結束後
67 {
68 label3.Text = DateTime.Now.ToLongTimeString();
69 }
70
71 private void button3_Click(object sender, EventArgs e) //開始BackgroundWorker的耗時操作
72 {
73 backgroundWorker1.RunWorkerAsync();
74 }
75
76
77 }
78 }
79