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");
相关推荐
CoderCodingNo1 分钟前
【GESP】C++一级真题 luogu-B4495, [GESP202603 一级] 交朋友
开发语言·c++
海寻山11 分钟前
Java内部类:4种类型+实战场景+面试避坑
java·开发语言·面试
梦游钓鱼17 分钟前
stl常用容器说明
开发语言·c++
踏着七彩祥云的小丑26 分钟前
Python——字符串常用操作
开发语言·python
成都易yisdong31 分钟前
基于C#和WMM2025模型的地磁参数计算器实现
开发语言·c#
Sss_Ass37 分钟前
在Qt Creator创建并编写第一个程序
开发语言·qt
预见AI1 小时前
C#索引器练习题
开发语言·计算机视觉·c#
农村小镇哥1 小时前
PHP数据传输流+上传条件+上传步骤
java·开发语言·php
电商API&Tina1 小时前
淘宝 / 京东关键词搜索 API 接入与实战用途教程|从 0 到 1 搭建电商选品 / 比价 / 爬虫替代系统
java·开发语言·数据库·c++·python·spring