【问题标题】:C# TPL for loop - limit number of threadsC# TPL for 循环 - 限制线程数
【发布时间】:2017-04-19 08:56:09
【问题描述】:

我只想使用 2 个线程来创建 for 循环。我试过这段代码:

ParallelOptions po = new ParallelOptions {
    MaxDegreeOfParallelism = 2
};

Parallel.For(0, width, po, x => {
    sb.Append(Thread.CurrentThread.ManagedThreadId);
    sb.Append(Environment.NewLine);
    for (int y = 0; y < height; y++) {
        double a = (double)(x - (width / 2)) / (double)(width / 4);
        double b = (double)(y - (height / 2)) / (double)(height / 4);
    }
});

但是当我显示 Thread.CurrentThread.ManagedThreadId 时,它会创建超过 2 个 id。我还尝试在循环之前添加此代码:

ThreadPool.SetMaxThreads(2, 2);
ThreadPool.SetMinThreads(2, 2);

但它也没有改变任何东西。有人可能知道我该如何解决这个问题?

【问题讨论】:

  • 我希望你不要在多线程环境中使用StringBuilder,因为它不是线程安全的
  • 我只用它来制作带有所有线程 id 的大字符串。你认为这个 StringBuilder 在运行超过 2 个线程时会出现问题吗?
  • 是的。只需使用Console.WriteLine(Environment.CurrentManagedThreadId )Trace.TraceInformation.....
  • 还是不行:/
  • @MarMosh 这并不是一个答案

标签: c# multithreading task-parallel-library


【解决方案1】:

MaxDegreeOfParallelism 设置将用于Parallel.For() 的最大同时 线程数。这并不意味着永远只会使用两个线程。

在执行Parallel.For() 期间,可以从线程池中分配不同的线程,因为线程池线程是专门为重用而设计的。

以下程序演示。如果你运行它,你会看到正在使用的不同线程的总数可以超过 2,但同时使用的线程总数永远不会超过 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();
        }
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-03-30
    • 2014-11-12
    • 2011-06-17
    • 1970-01-01
    • 1970-01-01
    • 2013-11-07
    • 1970-01-01
    相关资源
    最近更新 更多