.net 控制线程数量

通过两种方法:

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());
                }
            }
        }

    }

 

上一篇:任务调度器


下一篇:解决VScode的一些问题