一、Thread线程使用方法
- 初始化方法
Thread th1;
th1 = new Thread(方法名);
th1.IsBackground = true;
th1.Start();
- 传参
private void Test(object n){
string str1 = n as string;
MessageBox.Show(str1);
}
Thread th2
string str1 = “我是线程2”;
th2 = new Thread(Test);
th2.isBackground = true;
th2.Start(str1);
- 加入线程池
ThreadPool.QueueUserWorkItem(方法名);
- 关闭线程
Private void Form1_FormClosing(){
th1.Abort();
}
二、ThreadPool 线程使用方法
ThreadPool.QueueUserWorkItem((str)=> {代码块}, “线程参数”);
三、解决跨线程调用组件
- 使用一行代码解决(代码多不推荐)
CheckForIllegalCrossThreadCalls = false;
- 在线程调用的方法中组件使用委托
组件.BeginInvoke(new Action<变量类型>((变量)=>{代码块}), 形参);
textBox1.BeginInvoke(new Action<string>((str) => {
textBox1.Text += str;
}), "111111\r\n");