前言
众所周知,Thread类中的挂起线程和恢复线程微软已标记过时,因为可能会造成问题
| Resume() 恢复当前线程 |
已过时。 Resumes a thread that has been suspended. |
| Suspend() 挂起当前线程 |
已过时。 挂起线程,或者如果线程已挂起,则不起作用。 |
其他方式实现
一、ThreadWorkItem
class ThreadWorkItem { public int ThreadManagerId { get; set; } public Thread Thread { get; set; } public string ThreadName { get; set; } public bool Flag { get; set; } public ManualResetEvent ManualResetEvent { get; set; } }
二、C# Thread挂起线程和恢复线程的实现的两种方式
方式1:使用变量开关控制挂起线程和恢复线程,具体代码如下
public class Program { //线程工作集合 private static List<ThreadWorkItem> Works = new List<ThreadWorkItem>(); //方式1:使用变量开关控制挂起线程和恢复线程 private static void Main(string[] args) { ThreadWorkItem wItem = null; Thread t = null; var threadNum = 2; for (int i = 0; i < threadNum; i++) { t = new Thread(o=> { var w = o as ThreadWorkItem; if (w == null) return; while (true) { if (!w.Flag) { Console.WriteLine("我是线程:" + Thread.CurrentThread.Name); Thread.Sleep(1000); continue; } //避免CPU空转 Thread.Sleep(5000); } }); //$ C#6.0语法糖 t.Name = $"Hello I'am 线程:{i}-{t.ManagedThreadId}"; wItem = new ThreadWorkItem { Flag = false, Thread = t, ThreadManagerId = t.ManagedThreadId, ThreadName = t.Name }; Works.Add(wItem); t.Start(Works[i]); } //5秒后允许一个等待的线程继续。当前允许的是线程1 Thread.Sleep(5000); Works[0].Flag = true; Console.WriteLine($"thread-{Works[0].ThreadName} is 暂停"); //5秒后允许一个等待的线程继续。当前允许的是线程0,1 Thread.Sleep(5000); Works[0].Flag = false; Console.WriteLine($"thread-{Works[0].ThreadName} is 恢复"); } }