using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace DataService.ETL_ApiData { public class MultiTask { /// <summary> /// 最大线程数量 /// </summary> private int _maxTaskCount = 10; public MultiTask() { } public void StartTask() { List<Task> taskList = new List<Task>(); for (int i = 0; i < 20; i++) { //添加任务 taskList.Add(Task.Run(() => { OutputMessage(i.ToString()); })); //限制线程数量 if (taskList.Count > _maxTaskCount) { Task.WaitAny(taskList.ToArray()); taskList = taskList.Where(t => t.Status != TaskStatus.RanToCompletion).ToList(); } } //等待任务结束 Task.WaitAll(taskList.ToArray()); } private void OutputMessage(string id) { string message = string.Format(@"开始执行任务{0}",id); Console.WriteLine(message); } } }
标签:core,Task,System,任务,taskList,线程,using,多线程 From: https://www.cnblogs.com/damenge/p/17870410.html