使用 ThreadPool 执行多线程任务,控制并发数,避免线程过多导致性能下降。
using System.Threading; public class ThreadPoolDemo { private static int _completedTasks = 0; private static readonly ManualResetEvent _resetEvent = new ManualResetEvent(false); private const int _taskCount = 10; // 任务方法 private static void TaskMethod(object state) { int taskId = (int)state; Console.WriteLine($"任务 {taskId} 开始执行,线程ID: {Thread.CurrentThread.ManagedThreadId}"); Thread.Sleep(1000); // 模拟任务耗时 Console.WriteLine($"任务 {taskId} 执行完成"); // 任务完成计数 if (Interlocked.Increment(ref _completedTasks) == _taskCount) { _resetEvent.Set(); } } // 调用示例 public static void TestThreadPool() { Console.WriteLine("线程池任务开始"); // 提交任务到线程池 for (int i = 0; i < _taskCount; i++) { ThreadPool.QueueUserWorkItem(TaskMethod, i); } // 等待所有任务完成 _resetEvent.WaitOne(); Console.WriteLine("所有任务执行完毕"); _resetEvent.Close(); } }