C#中线程的使用(1)--Thread与ThreadPool
一、简介
简单记录一下c#中多线程的使用方法,在使用之前时候要弄明白几个问题,什么是进程?什么是线程?进程与线程之间是什么关系?
简单来说,一个运行的程序就是一个进程,一个进程可以包含多个线程,每个线程都是一个执行流,都拥有独立的寄存器和共享的代码存储区。
下面就来记录一下Thread与ThreadPool 的使用方法。
二、Thread的使用
2.1
public static void Main() { //方式1 Thread thread1 = new Thread(new ThreadStart(SayHello)); thread1.Start(); //方式2 Thread thread2 = new Thread(() => { Console.WriteLine("hello "); }); thread2.Start(); } private void SayHello() { Console.WriteLine("hello"); }
2.2
Thread thread = new Thread(Say); thread.Start("Hello");//启动线程 //方法声明 private static void Say(object obj) { Console.WriteLine(obj); }
2.3 当我们想要等待线程结束后再执行后面程序时,可以使用Join
thread.Join();//等待线程 直到结束 thread.Join(1000); // 等待线程 1s钟 1000 是指等待的时间
2.4
Func<int, int> threadStart = (num) => { int sum = 0; for (int i = 0; i < num; i++) { sum += i; } return sum; }; Action<int> action = (sum) => { Console.WriteLine(sum); }; this.ThreadContinueWith(threadStart, action); //封装方法 private void ThreadContinueWith(Func<int,int> threadStart, Action<int> actionCallback) { ThreadStart threadStart1 = new ThreadStart(() => { int sum = threadStart.Invoke(10000); actionCallback.Invoke(sum); }); Thread thread = new Thread(threadStart1); thread.Start(); }
2.5 Thread其他的操作
thread.IsBackground = true;//进程结束,线程也结束 thread.Abort();//终结线程 thread.Suspend();// 暂停线程,已弃用 thread.Resume();//恢复线程 ,已弃用
三、线程池ThreadPool的使用
3.1 使用线城池开启线程
//将方法排入队列以便执行 使用线程池执行方法 o为传递的参数,未传递参数时,o=null ThreadPool.QueueUserWorkItem(o => { for (int i = 0; i < 10; i++) { Thread.Sleep(500); Console.WriteLine(i); } }); //传递参数 ThreadPool.QueueUserWorkItem(o => { for (int i = 0; i < (int)o; i++) { Thread.Sleep(500); Console.WriteLine($"{i},{o}"); } },10);
3.2 线程池可以设置最大的线程数量
ThreadPool.SetMaxThreads(100, 100); //线程池中辅助线程的最大数目100,线程池中异步 I/O 线程的最大数目100 更改成功则会返回true ThreadPool.SetMinThreads(12, 12);
3.3 可以使用ManualResetEvent来控制线程的开关
//ManualResetEvent 如果为 true,则将初始状态设置为终止;如果为 false,则将初始状态设置为非终止。 ManualResetEvent manualResetEvent = new ManualResetEvent(true); //开关关闭 ThreadPool.QueueUserWorkItem(o => { Thread.Sleep(3000); manualResetEvent.Set();// 开关打开 }); manualResetEvent.WaitOne();//等待信号 Console.WriteLine("线程已结束");
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 单元测试从入门到精通
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 上周热点回顾(3.3-3.9)
· winform 绘制太阳,地球,月球 运作规律