当前位置:
凯发ag旗舰厅登录网址下载 >
编程语言
> c#
>内容正文
c#
c#基础,单线程,跨线程访问和线程带参数 -凯发ag旗舰厅登录网址下载
凯发ag旗舰厅登录网址下载
收集整理的这篇文章主要介绍了
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 ///
15 /// 单线程直接假死了
16 ///
17 ///
18 ///
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 ///
30 /// 新线程运行,窗体不假死
31 ///
32 ///
33 ///
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 ///
44 /// 循环计算方法,供新线程使用
45 ///
46 private void showcalculator()
47 {
48 for (int i = 0; i < 100000; i )
49 {//通过[调试]-[窗口]-[输出]显示打印值
50 console.writeline(i);
51 }
52 }
53 ///
54 /// 带参数的
55 ///
56 ///
57 ///
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 ///
75 /// 跨线程访问
76 ///
77 ///
78 ///
79 private void button1_click(object sender, eventargs e)
80 {
81 thread th = new thread(showmulti) { isbackground = true };
82 th.start();
83 }
84 ///
85 /// 解决跨线程访问报异常,不使用关闭跨线程检查
86 ///
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
- 上一篇: 女生考部队文职专业要求
- 下一篇: 18星瓢虫吃黄瓜吗?