线程:
帮助老板干活的,不会干扰老板的正常工作
如果一段代码的执行需要时间,那么必须开启一个新线程来执行,
如果不开线程,窗口会出现假死
开线程:
Thread th = new Thread(委托);
th.IsBackground = true; //设置后台线程
th.Start();
线程默认是不允许跨线程访问对象的
在构造函数中用Control.CheckForIllegalCrossThreadCalls = false; 可以允许跨线程访问对象。
关闭线程:
th.Abort();
线程最多可以执行一个参数的方法,这个参数必须是object类型
利用线程做一个三级连动的小程序:
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading; using System.Threading.Tasks; using System.Windows.Forms; namespace 线程联系__小程序___2017_5_4 { public partial class Form1 : Form { public Form1() { InitializeComponent(); Control.CheckForIllegalCrossThreadCalls = false; } Thread th = null; Thread th1 = null; Thread th2 = null; private void button1_Click(object sender, EventArgs e) { th = new Thread(test1); th.IsBackground = true; th.Start(); th1 = new Thread(test2); th1.IsBackground = true; th1.Start(); th2 = new Thread(test3); th2.IsBackground = true; th2.Start(); } private void button2_Click(object sender, EventArgs e) { th.Abort(); th1.Abort(); th2.Abort(); } public void test1() { Random r = new Random(); string[] name = new string[] { "郑倩", "徐强", "子君", "子轩", "郑剑" }; while (true) { int a = r.Next(1, name.Length); textBox1.Text = name[a]; Thread.Sleep(100); } } public void test2() { Random r = new Random(); string[] city = new string[] { "博兴", "张店", "马桥", "济南", "青岛" }; while (true) { int b = r.Next(1, city.Length); textBox2.Text = city[b]; Thread.Sleep(100); } } public void test3() { Random r = new Random(); string[] events = new string[] { "吃汉堡", "旅游", "淘气", "上学", "写代码", "玩" }; while (true) { int c = r.Next(1, events.Length); textBox3.Text = events[c]; Thread.Sleep(100); } } } }