C#中创建线程,创建带参数的线程
线程操作主要用到Thread类,他是定义在System.Threading.dll下。使用时需要添加这一个引用。该类提供给我们四个重载的构造函
构造函数定义:
无参数委托
[SecuritySafeCritical] public Thread(ThreadStart start); [SecuritySafeCritical] public Thread(ThreadStart start, int maxStackSize);
有一个参数object委托
[SecuritySafeCritical] public Thread(ParameterizedThreadStart start); [SecuritySafeCritical] public Thread(ParameterizedThreadStart start, int maxStackSize); // maxStackSize: // 线程要使用的最大堆栈大小(以字节为单位);如果为 0 则使用可执行文件的文件头中指定的默认最大堆栈大小。重要地,对于部分受信任的代码,如果 maxStackSize // 大于默认堆栈大小,则将其忽略。不引发异常。
一、创建没有参数传入线程
//创建没有参数的线程 Thread thread = new Thread(new ThreadStart(ThreadMethod)); //或者 //Thread thread = new Thread(ThreadMethod); thread.Start(); Console.WriteLine("代码执行完成");
//线程方法定义 public static void ThreadMethod() { Console.WriteLine("当前线程ID:{0},当前线程名称:{1}", Thread.CurrentThread.ManagedThreadId, Thread.CurrentThread.Name); while (true) { Console.WriteLine(DateTime.Now); Thread.Sleep(1000); } }
二、创建一个参数传入object类型的线程
public static void Init() { //创建一个参数的线程 //ParameterizedThreadStart 指定传入的类型是object for (int i = 0; i < 3; i++) { Thread thread = new Thread(new ParameterizedThreadStart(ThreadMethod)); object obj = i * 10; thread.Start(obj); } } //定义线程方法 public static void ThreadMethod(object number) { int i = (int)number; while (true) { i++; Console.WriteLine("当前线程ID:{0},number={1}", Thread.CurrentThread.ManagedThreadId, i); Thread.Sleep(2000); } }
三、创建使用对象实例方法,创建多个参数传入情况的线程
public static void Init() { //创建多个传入参数的线程 for (int i = 1; i < 4; i++) { Calculator cal = new Calculator(i, i * 100); Thread thread = new Thread(new ThreadStart(cal.Add)); thread.Start(); } }
public class Calculator { public int X { get; set; } public int Y { get; set; } public Calculator(int x, int y) { this.X = x; this.Y = y; } //定义线程执行方法 public void Add() { int i = 0; while (i < 2) { i++; Console.WriteLine("当前线程ID:{0},{1}+{2}={3}", Thread.CurrentThread.ManagedThreadId, X, Y, X + Y); Thread.Sleep(1000); } } }
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· winform 绘制太阳,地球,月球 运作规律
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· AI与.NET技术实操系列(五):向量存储与相似性搜索在 .NET 中的实现
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 超详细:普通电脑也行Windows部署deepseek R1训练数据并当服务器共享给他人