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");
相关推荐
jaysee-sjc2 分钟前
十七、Java 高级技术入门全解:JUnit、反射、注解、动态代理
java·开发语言·算法·junit·intellij-idea
Dxy123931021615 分钟前
Python使用SymSpell详解:打造极速拼写检查引擎
开发语言·python
时寒的笔记19 分钟前
js7逆向案例_禁止f12打开&sojson打开
开发语言·javascript·ecmascript
大鹏说大话23 分钟前
什么是“过早优化”?
开发语言
码云数智-园园24 分钟前
RESTful API vs GraphQL:设计哲学、性能博弈与选型指南
开发语言
每天吃饭的羊32 分钟前
nest,java对比
java·开发语言
sycmancia33 分钟前
Qt——登录对话框
开发语言·qt
专注VB编程开发20年33 分钟前
WebView2同时执行多个Promise异步任务性能损失1毫秒以内
开发语言
froginwe1134 分钟前
Perl 目录操作指南
开发语言
架构师老Y36 分钟前
010:API网关调试手记:路由、认证与限流的那些坑
开发语言·前端·python