zoukankan      html  css  js  c++  java
  • 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();
            }
        }
    }
  • 相关阅读:
    search方法的使用
    边界字符的使用
    重复数量限定符
    常用匹配符
    使用JS快速读取TXT文件
    基于jq和纯js的 读取本地.txt文件的方法
    Linux中的du和df命令
    HSSFWorkbook
    el表达式
    eclipse 导入web项目时常见错误
  • 原文地址:https://www.cnblogs.com/zeroone/p/6770623.html
Copyright © 2011-2022 走看看