首页 > 代码库 > TPL中限制进程数量
TPL中限制进程数量
The MaxDegreeOfParallelism
sets the maximum number of simultaneous threads that will be used for the Parallel.For()
. It does not mean that only two threads will ever be used.
Different threads can be allocated from the threadpool during execution of the Parallel.For()
, since threadpool threads are specifically designed to be reused.
The following program demonstrates. If you run it, you‘ll see that the total number of different threads being used can exceed 2, but the total number of threads being used simultaneously never exceeds 2.
using System;using System.Collections.Concurrent;using System.Threading;using System.Threading.Tasks;namespace ConsoleApp1{ class Program { static void Main() { ParallelOptions po = new ParallelOptions { MaxDegreeOfParallelism = 2 }; var activeThreads = new ConcurrentDictionary<int, bool>(); Parallel.For(0, 100, po, x => { activeThreads[Thread.CurrentThread.ManagedThreadId] = true; Console.WriteLine("Active threads: " + string.Join(", ", activeThreads.Keys)); Thread.Sleep(200); activeThreads.TryRemove(Thread.CurrentThread.ManagedThreadId, out bool unused); }); Console.ReadLine(); } }}
TPL中限制进程数量
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。