标签:最大 int lin max string rgb pre actions style
通过两种方法:
TaskFactory/ParallelOptions
class Program { static void Main(string[] args) { int num = 10; ControlTaskNum(num); UseParallelOptions(num); } /// <summary> /// 通过 ParallelOptions 控制线程数 /// </summary> /// <param name="num"></param> private static void UseParallelOptions(int num) { List<Action> actions = new List<Action>(); for (int i = 0; i < 10000; i++) { actions.Add(() => Console.WriteLine(i)); } ParallelOptions parallelOptions = new ParallelOptions(); parallelOptions.MaxDegreeOfParallelism = num; Parallel.Invoke(parallelOptions, actions.ToArray()); } /// <summary> /// 通过 TaskFactory 控制线程数 /// </summary> /// <param name="v">最大线程</param> private static void ControlTaskNum(int v) { TaskFactory taskFactory = new TaskFactory(); List<Task> tasks = new List<Task>(); for (int i = 0; i < 10000; i++) { tasks.Add(taskFactory.StartNew(() => Console.WriteLine(i))); if (tasks.Count >=v) { tasks.Where(t => t.IsCompleted && !t.IsCanceled && !t.IsFaulted).ToList(); Task.WaitAny(tasks.ToArray()); } } } }
标签:最大 int lin max string rgb pre actions style
原文地址:https://www.cnblogs.com/Zingu/p/14640482.html