C# 窗体应用(.FET Framework) 线程操作方法

一、Thread线程使用方法

  1. 初始化方法
Thread th1;
th1 = new Thread(方法名);
th1.IsBackground = true;
th1.Start();
  1. 传参
///定义一个object接受参数的方法
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);  // 这边在启动的时候传递参数
  1. 加入线程池
ThreadPool.QueueUserWorkItem(方法名);
  1. 关闭线程
Private void Form1_FormClosing(){
   th1.Abort();
}

二、ThreadPool 线程使用方法

ThreadPool.QueueUserWorkItem((str)=> {代码块}, “线程参数”);

三、解决跨线程调用组件

  1. 使用一行代码解决(代码多不推荐)
// 在 Form1() 方法中加入以下代码
CheckForIllegalCrossThreadCalls = false;
  1. 在线程调用的方法中组件使用委托
组件.BeginInvoke(new Action<变量类型>((变量)=>{代码块}), 形参);
textBox1.BeginInvoke(new Action<string>((str) => {
    textBox1.Text += str;
}), "111111\r\n");
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值