Parallel.ForEach keeps spawning new threads

前端 未结 3 1417
天命终不由人
天命终不由人 2020-12-05 15:24

While I was using Parallel.ForEach in my program, I found that some threads never seemed to finish. In fact, it kept spawning new threads over and over, a behaviour that I w

3条回答
  •  被撕碎了的回忆
    2020-12-05 15:56

    I've posted the follow-up question "How to count the amount of concurrent threads in .NET application?"

    If to count the threads directly, their number in Parallel.For() mostly ((very rarely and insignificantly decreasing) only increases and is not releleased after loop completion.

    Checked this in both Release and Debug mode, with

    ParallelOptions po = new ParallelOptions
    {
      MaxDegreeOfParallelism = Environment.ProcessorCount
    };
    

    and without

    The digits vary but conclusions are the same.

    Here is the ready code I was using, if someone wants to play with:

    using System;
    using System.Collections.Generic;
    using System.Diagnostics;
    using System.Linq;
    using System.Threading;
    using System.Threading.Tasks;
    
    namespace Edit4Posting
    {
    public class Node
    {
    
      public Node Previous { get; private set; }
      public Node(Node previous)
      {
        Previous = previous;
        }
      }
      public class Edit4Posting
      {
    
        public static void Main(string[] args)
        {
          int concurrentThreads = 0;
          int directThreadsCount = 0;
          int diagThreadCount = 0;
    
          var jobs = Enumerable.Range(0, 160);
          ParallelOptions po = new ParallelOptions
          {
            MaxDegreeOfParallelism = Environment.ProcessorCount
          };
          Parallel.ForEach(jobs, po, delegate(int jobNr)
          //Parallel.ForEach(jobs, delegate(int jobNr)
          {
            int threadsRemaining = Interlocked.Increment(ref concurrentThreads);
    
            int heavyness = jobNr % 9;
    
            //Give the processor and the garbage collector something to do...
            List nodes = new List();
            Node current = null;
            //for (int y = 0; y < 1024 * 1024 * heavyness; y++)
            for (int y = 0; y < 1024 * 24 * heavyness; y++)
            {
              current = new Node(current);
              nodes.Add(current);
            }
            //*******************************
            directThreadsCount = Process.GetCurrentProcess().Threads.Count;
            //*******************************
            threadsRemaining = Interlocked.Decrement(ref concurrentThreads);
            Console.WriteLine("[Job {0} complete. {1} threads remaining but directThreadsCount == {2}",
              jobNr, threadsRemaining, directThreadsCount);
          });
          Console.WriteLine("FINISHED");
          Console.ReadLine();
        }
      }
    }
    

提交回复
热议问题