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");
相关推荐
7ioik15 分钟前
什么是线程池?线程池的作用?线程池的四种创建方法?
java·开发语言·spring
寻星探路19 分钟前
JavaSE重点总结后篇
java·开发语言·算法
Charles_go1 小时前
C#中级8、什么是缓存
开发语言·缓存·c#
松涛和鸣2 小时前
14、C 语言进阶:函数指针、typedef、二级指针、const 指针
c语言·开发语言·算法·排序算法·学习方法
智商低情商凑7 小时前
Go学习之 - Goroutines和channels
开发语言·学习·golang
半桶水专家7 小时前
Go 语言时间处理(time 包)详解
开发语言·后端·golang
编程点滴7 小时前
Go 重试机制终极指南:基于 go-retry 打造可靠容错系统
开发语言·后端·golang
实心儿儿7 小时前
C++ —— 模板进阶
开发语言·c++
萧鼎7 小时前
Python PyTesseract OCR :从基础到项目实战
开发语言·python·ocr
二川bro8 小时前
第57节:Three.js企业级应用架构
开发语言·javascript·架构