当我在我的程序中使用Parallel.ForEach时,我发现有些线程似乎永远不会完成.事实上,它一直在反复产生新线程,这种行为是我没想到的,绝对不想要的.
我能够使用以下代码重现此行为,就像我的"真实"程序一样,它们都使用处理器和内存(.NET 4.0代码):
public class Node
{
public Node Previous { get; private set; }
public Node(Node previous)
{
Previous = previous;
}
}
public class Program
{
public static void Main(string[] args)
{
DateTime startMoment = DateTime.Now;
int concurrentThreads = 0;
var jobs = Enumerable.Range(0, 2000);
Parallel.ForEach(jobs, delegate(int jobNr)
{
Interlocked.Increment(ref concurrentThreads);
int heavyness = jobNr % 9;
//Give the processor and the garbage collector something to do...
List<Node> nodes = new List<Node>();
Node current = null;
for (int …Run Code Online (Sandbox Code Playgroud) .net c# concurrency parallel-extensions task-parallel-library