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 ThreadFormTest { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void button1_Click(object sender, EventArgs e) { for (int i = 0; i < 100; i++) { lbl_state.Text = i.ToString(); } } private void button2_Click(object sender, EventArgs e) { //调用TaskList类的实例成员方法DoTaskB TaskList task = new TaskList(); Thread t1 = new Thread(task.DoTaskB); t1.Start(); } private void button3_Click(object sender, EventArgs e) { Thread t1 = new Thread(TaskList.DoTaskA); t1.Start(); } private void button4_Click(object sender, EventArgs e) { TaskList task = new TaskList(); Thread t1 = new Thread(task.StcDoTaskB); t1.Start("实例方法"); } private void button5_Click(object sender, EventArgs e) { Thread t1 = new Thread(TaskList.StcDoTaskA); t1.Start("静态方法"); } } }
TaskList.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Windows.Forms; namespace ThreadFormTest { public class TaskList { public void DoTaskB() { MessageBox.Show("我是实例成员方法"); } public static void DoTaskA() { MessageBox.Show("我是静态成员方法"); } public void StcDoTaskB(object date) { MessageBox.Show(date.ToString()); } public static void StcDoTaskA(object date) { MessageBox.Show(date.ToString()); } } }
form1界面设计
Thread名字.Suspend();
Thread名字.Resume();
Thread名字.Abort();
Thread名字.Join();
前台线程和后台线程的区别在于,后台线程会随着主线程的结束而结束,而前台线程,应用程序要等待前台线程结束应用程序才能结束。当给IsBackground属性赋值true时就指明了你建立的是后台进程,如果你建立线程时不指明类型,呢么默认是前台进程。
ThreadPriority枚举:
Highest、AboveNormal、BelowNormal、Lowest
不同的线程在相同的时间要求被执行。他们之间对资源就会产生并发
锁:用lock语句锁定在线程中共享的变量,另一个线程就必须等待倍锁定的解除
死锁:在死锁中,至少有两个线程倍挂起,等待对方解锁。由于两个线程都在等待对方,就出现了死锁,线程将无限等待下去。
lock(expression)//锁定expression,不被其他线程修改到
{
statement_block
}