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

一、Thread线程使用方法

  1. 初始化方法
cs 复制代码
Thread th1;
th1 = new Thread(方法名);
th1.IsBackground = true;
th1.Start();
  1. 传参
cs 复制代码
///定义一个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. 加入线程池
cs 复制代码
ThreadPool.QueueUserWorkItem(方法名);
  1. 关闭线程
cs 复制代码
Private void Form1_FormClosing(){
   th1.Abort();
}

二、ThreadPool 线程使用方法

cs 复制代码
ThreadPool.QueueUserWorkItem((str)=> {代码块}, "线程参数");

三、解决跨线程调用组件

  1. 使用一行代码解决(代码多不推荐)
cs 复制代码
// 在 Form1() 方法中加入以下代码
CheckForIllegalCrossThreadCalls = false;
  1. 在线程调用的方法中组件使用委托
cs 复制代码
组件.BeginInvoke(new Action<变量类型>((变量)=>{代码块}), 形参);
cs 复制代码
textBox1.BeginInvoke(new Action<string>((str) => {
    textBox1.Text += str;
}), "111111\r\n");
相关推荐
Tony Bai1 小时前
高并发后端:坚守 Go,还是拥抱 Rust?
开发语言·后端·golang·rust
wjs20242 小时前
Swift 类型转换
开发语言
秃了也弱了。2 小时前
python实现定时任务:schedule库、APScheduler库
开发语言·python
weixin_440730502 小时前
java数组整理笔记
java·开发语言·笔记
Thera7772 小时前
状态机(State Machine)详解:原理、优缺点与 C++ 实战示例
开发语言·c++
niucloud-admin3 小时前
java服务端——controller控制器
java·开发语言
夏幻灵4 小时前
JAVA基础:基本数据类型和引用数据类型
java·开发语言
cike_y4 小时前
Spring-Bean的作用域&Bean的自动装配
java·开发语言·数据库·spring
十八度的天空5 小时前
第01节 Python的基础语法
开发语言·python
我是唐青枫5 小时前
深入理解 C#.NET Interlocked.Increment:原子操作的核心
c#·.net