c# 并行编程设置最大进程数

 

 

 

using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace MyExec
{
    class Program
    {
        static void Main(string[] args)
        {
            //创建由多个线程同时访问的键/值对的线程安全集合
            var activeThreads = new ConcurrentDictionary<int, bool>();
            Parallel.For(0, 100, new ParallelOptions() {
                //获取或设置并行允许的最大并行度,即并行允许的最大进程数
                MaxDegreeOfParallelism = 2
            }, x =>
            {
                activeThreads[Thread.CurrentThread.ManagedThreadId] = true;
                Console.WriteLine($"x:{x},active threads:{string.Join(", ", activeThreads.Keys)}");
                Thread.Sleep(200);
                //尝试移除(如果线程ID在其他并行处理中已移除,这儿的unused为false,否则为true)
                activeThreads.TryRemove(Thread.CurrentThread.ManagedThreadId, out bool unused);
            });
            Console.WriteLine("end");
            Console.ReadKey();
        }
    }
}

 

posted @ 2017-06-03 09:29  lcawen  阅读(710)  评论(0)    收藏  举报