C#多线程学习
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
TextBox.CheckForIllegalCrossThreadCalls = false;
}
//单线程和多线程
void count()
{
Stopwatch sw = new Stopwatch();
sw.Start();
for (int i = 0; i <900000000;i++)
{
}
sw.Stop();
MessageBox.Show(sw.ElapsedMilliseconds.ToString());//执行时间
}
//线程重入
void add()
{
int num = 0;
for (int i = 0; i < 1000; i++)
{
textBox1.Text = num.ToString();
Console.WriteLine(Thread.CurrentThread.Name+" num="+num);
num++;
}
}
//线程执行带参数的方法
void show(object name)//object类型
{
MessageBox.Show("name="+name);
}
//线程执行带多个参数的方法
void show2(object name)
{
List<string> list=name as List<string>;
foreach(string li in list)
{
MessageBox.Show(li);
}
}
private void button1_Click(object sender, EventArgs e)
{
count();//单线程
}
private void button2_Click(object sender, EventArgs e)
{
Thread thread1 = new Thread(count);
thread1.Start();//多线程
thread1.IsBackground = true;//设为后台线程,主线程关闭后停止执行
}
private void button3_Click(object sender, EventArgs e)
{
Thread thread1 = new Thread(add);
thread1.Name ="t1";
thread1.IsBackground = true;
thread1.Start();
Thread thread2 = new Thread(add);
thread2.Name = "t2";
thread2.IsBackground = true;
thread2.Start();
}
private void button4_Click(object sender, EventArgs e)
{
Thread thread1 = new Thread(show);
thread1.IsBackground = true;
thread1.Start("周杰伦");
}
private void button5_Click(object sender, EventArgs e)
{
Thread thread1 = new Thread(show2);
thread1.IsBackground = true;
thread1.Start(new List<string> { "周杰伦", "刘德华" });
}
}