码迷,mamicode.com
首页 > 系统相关 > 详细

TPL中限制进程数量

时间:2017-04-26 21:31:42      阅读:233      评论:0      收藏:0      [点我收藏+]

标签:use   ati   des   using   dem   rate   key   designed   exe   

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中限制进程数量

标签:use   ati   des   using   dem   rate   key   designed   exe   

原文地址:http://www.cnblogs.com/zeroone/p/6770623.html

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