码迷,mamicode.com
首页 > 编程语言 > 详细

.net 控制线程数量

时间:2021-04-12 11:41:02      阅读:0      评论:0      收藏:0      [点我收藏+]

标签:最大   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());
                }
            }
        }

    }

 

.net 控制线程数量

标签:最大   int   lin   max   string   rgb   pre   actions   style   

原文地址:https://www.cnblogs.com/Zingu/p/14640482.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!