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");
相关推荐
王琦031821 分钟前
Python 函数详解
开发语言·python
胡伯来了27 分钟前
13. Python打包工具- setuptools
开发语言·python
小鸡吃米…35 分钟前
Python 中的多层继承
开发语言·python
deng-c-f1 小时前
Linux C/C++ 学习日记(53):原子操作(二):实现shared_ptr
开发语言·c++·学习
wanghowie1 小时前
01.07 Java基础篇|函数式编程与语言新特性总览
java·开发语言·面试
Cricyta Sevina1 小时前
Java IO 基础理论知识笔记
java·开发语言·笔记
MyBFuture1 小时前
C#接口与抽象类:关键区别详解
开发语言·c#·visual studio
晨晖22 小时前
简单排序c语言版
c语言·开发语言
MediaTea2 小时前
大学 Python 编程基础(合集)
开发语言·python
墨雪不会编程2 小时前
C++ string 详解:STL 字符串容器的使用技巧
java·开发语言·c++