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");
相关推荐
hez20108 小时前
在 .NET 上构建超大托管数组
c#·.net·.net core·gc·clr
雨落倾城夏未凉6 天前
第四章c#方法-参数数组和可选参数(16)
后端·c#
唐青枫7 天前
线程不是越多越快:C#.NET Thread 生命周期、同步与后台工作线程实战
c#·.net
唐青枫8 天前
别只会反射:C#.NET Emit 动态生成代码实战详解
c#·.net
咕白m6258 天前
.NET 环境下 Word 超链接批量提取方案
c#·.net
用户91721561902118 天前
C# 通信协议增量解析:用状态机处理半包和粘包
c#
小码编匠9 天前
C# 工控上位机必备:数据转换工具类与十个核心模块
后端·c#·.net
唐青枫11 天前
别再乱用 StartNew:C#.NET TaskFactory 任务调度实战详解
c#·.net
Artech11 天前
[MAF预定义的AIContextProvider-03]ChatHistoryMemoryProvider——赋予Agent从经验中学习的能力
ai·c#·agent·memory·maf
Scout-leaf13 天前
C#摸鱼实录——IoC与DI案例详解
c#