多线程操作一直用ThreadPool.QueueUserWorkItem比较多,今天想到用这个方式实现,控制并发线程的数量。
主要思路是:
1.声明开启的线程数 int threadCount = 2;
2.创建一个泛型集合List<TaskInfo> workingList = new List<TaskInfo>(); 需要开启多少个线程,就从Queue里取几个taskInfo,添加到workingList,同时,把TaskInfo.IsBusy置为true.
3.在子线程中,执行完成时,再把TaskInfo.IsBusy置为false.
4.在主线程中,循环往workingList中放入TaskInfo 对象, 并通过判断TaskInfo.isBusy, 移除执行完成的TaskInfo对象。
代码如下,如有任何建议,还望不吝赐教。
public class TaskInfo { public bool IsBusy { get; set; } public int ID { get; set; } } public class Test { public void Work(object obj) { var taskInfo = obj as TaskInfo; //Do something ... Thread.Sleep(5000); taskInfo.IsBusy = false; } public void Test_MultyThread() { int threadCount = 2; Queue<TaskInfo> taskQueue = new Queue<TaskInfo>(); taskQueue.Enqueue(new TaskInfo() { ID = 1 }); taskQueue.Enqueue(new TaskInfo() { ID = 2 }); taskQueue.Enqueue(new TaskInfo() { ID = 3 }); taskQueue.Enqueue(new TaskInfo() { ID = 4 }); taskQueue.Enqueue(new TaskInfo() { ID = 5 }); List<TaskInfo> workingList = new List<TaskInfo>(); while (taskQueue.Count > 0) { if (workingList.Count < threadCount) { var taskInfo = taskQueue.Dequeue(); taskInfo.IsBusy = true; workingList.Add(taskInfo); Console.WriteLine("Processing ID: {0}", taskInfo.ID); ThreadPool.QueueUserWorkItem(new WaitCallback(Work), taskInfo); } else { if (workingList.Any(x => !x.IsBusy)) { workingList.RemoveAll(x => !x.IsBusy); } else { Console.ForegroundColor = ConsoleColor.Yellow; Console.WriteLine("==> Waiting for free thread ..."); Console.ResetColor(); Thread.Sleep(1000); } } } } }
时间: 2024-10-12 19:09:48