c#基础,单线程,跨线程访问和线程带参数
生活随笔
收集整理的這篇文章主要介紹了
c#基础,单线程,跨线程访问和线程带参数
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
1 using System;
2 using System.Collections.Generic;
3 using System.Threading;
4 using System.Windows.Forms;
5
6 namespace 線程和跨線程
7 {
8 public partial class Form1 : Form
9 {
10 public Form1()
11 {
12 InitializeComponent();
13 }
14 /// <summary>
15 /// 單線程直接假死了
16 /// </summary>
17 /// <param name="sender"></param>
18 /// <param name="e"></param>
19 private void btnAlone_Click(object sender, EventArgs e)
20 {
21 for (int i = 0; i < 100000; i++)
22 {
23 //通過[調試]-[窗口]-[輸出]顯示打印值
24 Console.WriteLine(i);
25 }
26 }
27
28
29 /// <summary>
30 /// 新線程運行,窗體不假死
31 /// </summary>
32 /// <param name="sender"></param>
33 /// <param name="e"></param>
34 private void btnNew_Click(object sender, EventArgs e)
35 {
36 Thread th = new Thread(ShowCalculator)
37 {
38 IsBackground = true
39 };
40 th.Start();
41
42 }
43 /// <summary>
44 /// 循環計算方法,供新線程使用
45 /// </summary>
46 private void ShowCalculator()
47 {
48 for (int i = 0; i < 100000; i++)
49 {//通過[調試]-[窗口]-[輸出]顯示打印值
50 Console.WriteLine(i);
51 }
52 }
53 /// <summary>
54 /// 帶參數的
55 /// </summary>
56 /// <param name="sender"></param>
57 /// <param name="e"></param>
58 private void btnParameters_Click(object sender, EventArgs e)
59 {
60 List<int> list = new List<int>() { 1, 2, 3, 4, 5 };
61 ParameterizedThreadStart parThreadStart = new ParameterizedThreadStart(ShowParameters);
62 Thread th = new Thread(parThreadStart) { IsBackground = true };
63 th.Start(list);
64 }
65 private void ShowParameters(object obj)
66 {
67 //線程中的參數只能是Object
68 List<int> result = obj as List<int>;
69 foreach (var item in result)
70 {
71 MessageBox.Show(item.ToString());
72 }
73 }
74 /// <summary>
75 /// 跨線程訪問
76 /// </summary>
77 /// <param name="sender"></param>
78 /// <param name="e"></param>
79 private void button1_Click(object sender, EventArgs e)
80 {
81 Thread th = new Thread(ShowMulti) { IsBackground = true };
82 th.Start();
83 }
84 /// <summary>
85 /// 解決跨線程訪問報異常,不使用關閉跨線程檢查
86 /// </summary>
87 private void ShowMulti()
88 {
89 int first = 0;
90 for (int i = 0; i < 10; i++)
91 {
92 first = i;
93 }
94 //是否要對lbl控件進行跨線程
95 if (this.lblShow.InvokeRequired)
96 {
97 //對委托中的數據類型驗證
98 this.lblShow.Invoke(new Action<Label, string>(ShowLableValue), this.lblShow, first.ToString());
99 }
100 else
101 {
102 this.lblShow.Text = first.ToString();
103 }
104 }
105 /// <summary>
106 /// 把值寫到控件中
107 /// </summary>
108 /// <param name="lbl"></param>
109 /// <param name="value"></param>
110 private void ShowLableValue(Label lbl, string value)
111 {
112 lbl.Text = value;
113 }
114
115 private void Form1_Load(object sender, EventArgs e)
116 {
117 //關閉跨進程檢查
118 //Label.CheckForIllegalCrossThreadCalls = false;
119 //改用委托方法實現
120 }
121 }
122 }
?
轉載于:https://www.cnblogs.com/sighful/p/8981007.html
總結
以上是生活随笔為你收集整理的c#基础,单线程,跨线程访问和线程带参数的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 女生考部队文职专业要求
- 下一篇: 18星瓢虫吃黄瓜吗?