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");
相关推荐
hez201021 小时前
Runtime Async - 步入高性能异步时代
c#·.net·.net core·clr
mudtools1 天前
.NET驾驭Word之力:玩转文本与格式
c#·.net
唐青枫2 天前
C#.NET 数据库开发提速秘籍:SqlSugar 实战详解
c#·.net
mudtools2 天前
.NET驾驭Word之力:理解Word对象模型核心 (Application, Document, Range)
c#·.net
侃侃_天下2 天前
最终的信号类
开发语言·c++·算法
echoarts2 天前
Rayon Rust中的数据并行库入门教程
开发语言·其他·算法·rust
Aomnitrix2 天前
知识管理新范式——cpolar+Wiki.js打造企业级分布式知识库
开发语言·javascript·分布式
大飞pkz2 天前
【设计模式】C#反射实现抽象工厂模式
设计模式·c#·抽象工厂模式·c#反射·c#反射实现抽象工厂模式
每天回答3个问题3 天前
UE5C++编译遇到MSB3073
开发语言·c++·ue5
伍哥的传说3 天前
Vite Plugin PWA – 零配置构建现代渐进式Web应用
开发语言·前端·javascript·web app·pwa·service worker·workbox