C#---线程2
来源:互联网 发布:米哈伊洛维奇 知乎 编辑:程序博客网 时间:2024/06/05 16:44
C#---线程2
1、线程执行带参数的方法
新建一个C#WINFORM程序,在窗体上添加一个按钮。
Form1.cs代码为:
using System;using System.Collections.Generic;using System.ComponentModel;using System.Data;using System.Drawing;using System.Linq;using System.Text;using System.Windows.Forms;using System.Threading; //线程命名空间namespace 线程2{ public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void button1_Click(object sender, EventArgs e) { Thread th = new Thread(Test); th.IsBackground = true; th.Start(); } private void Test(string s)//Test方法带参数 { for (int i = 0; i < 10000;i++ ) { Console.WriteLine(i); } } }}
程序会报错:
注意:(1)如果线程的执行方法需要参数,那么要求这个参数必须是object类型。
将Form1.cs代码改为:
using System;using System.Collections.Generic;using System.ComponentModel;using System.Data;using System.Drawing;using System.Linq;using System.Text;using System.Windows.Forms;using System.Threading; //线程命名空间namespace 线程2{ public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void button1_Click(object sender, EventArgs e) { Thread th = new Thread(Test); th.IsBackground = true; th.Start("123");//Test()方法传参数时传给Start() } private void Test(object s) { string str = (string)s; for (int i = 0; i <10000;i++ ) { Console.WriteLine(i); } } }}
2、实例---摇奖机
(1)新建一个C#WINFORM程序,在窗体上添加一个按钮和三个label控件。
(2)Form1.cs代码为:
using System;using System.Collections.Generic;using System.ComponentModel;using System.Data;using System.Drawing;using System.Linq;using System.Text;using System.Windows.Forms;using System.Threading; //线程命名空间namespace 线程2{ public partial class Form1 : Form { public Form1() { InitializeComponent(); } bool b = false; //启停标志 Thread th; private void button1_Click(object sender, EventArgs e) { if (b==false) { b = true; button1.Text = "停止"; //开始后button变为停止 th = new Thread(playGame); th.IsBackground = true; th.Start(); } else { b = false; button1.Text = "开始"; } } private void playGame() //产生随机数 { Random r = new Random(); while (b) { label1.Text = r.Next(0, 10).ToString(); //为三个label分别赋值0-10之间随机数 label2.Text = r.Next(0, 10).ToString(); label3.Text = r.Next(0, 10).ToString(); } } private void Form1_Load(object sender, EventArgs e) { Control.CheckForIllegalCrossThreadCalls = false; // } private void Form1_FormClosing(object sender, FormClosingEventArgs e) { if (th != null) { th.Abort(); //结束这个线程 } } }}
运行效果
0 0
- C#---线程2
- c/c++线程--2线程同步
- Linux C线程总结(2)
- 【C#】线程与线程
- C -线程
- Linux C编程--线程操作2--线程同步详解
- 线程1打印A,线程2打印B,线程3打印C,依次打印10遍
- c++/c实现线程池
- 【C/C++】什么是线程安全
- C#lock线程同步
- c下的线程
- ThreadPool 线程池[c#]
- c#线程与枚举
- ThreadPool 线程池[c#]
- c# 实现线程
- ThreadPool 线程池[c#]
- linux C 线程学习
- c实现线程池
- TCP中的四种定时器
- CentOS 7 编译安装PHP7
- 京京_fieldset添加表格样式
- Struts2总结---数据封装机制 (10)
- 线程学习--实现Runnable接口
- C#---线程2
- 如何创建多线程
- python opencv 入门 加载视频 (2)
- 前端学习(四)
- SpringMVC上传文件的三种方式
- poj 2387 Til the Cows Come Home
- MP与OMP方法
- 关于分治的小例子便于理解
- js实现类似淘宝继续拖动查看详情的弹簧效果