C#多線程操作控制項的兩種安全方式(委託方式和BackgroundWorker控制項方式)

來源:互聯網
上載者:User

實現的功能是

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

 

 

 

 

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.