Parallel.For 如何获取循环中使用的线程数?

Parallel.For how to get number of threads that are using in loop?

我有一个关于 Parallel.For 方法的问题。

我想在图像处理算法中使用1到4个线程进行比较。我这样设置 Parallel.For

        ParallelOptions po = new ParallelOptions();
        po.MaxDegreeOfParallelism = 4;

        Parallel.For(0, height - 1, po, y =>
        {
            int offset = y * stride; //row
            for (int x = 0; x < width - 1; x++)
            {
                //do stuff here
            }
         });

时间按Stopwatchclass.

计算
var stopwatch = Stopwatch.StartNew();
MethodWithParallelFor.Execute();
stopwatch.Stop();

我的问题是,为什么当我将 MaxDegreeOfParallelism 设置为任何值时(我的 CPU 有 8 个线程)我得到的时间完全相同?当我将 Degree 设置为 1 或 4 时,我得到相同的执行时间。

那么,如何调试Parallel.For获取信息,我的循环中有多少个线程运行?如何强制程序使用我想要的那么多线程?如果需要,我可以分享我的完整代码

我在 C# 7.3 和 WPF 4.6.2 中实现了我的测试程序

如果您想知道在任何给定时间您的 Parallel.For 中同时有多少个线程 运行,您可以使用 Interlocked.Increment 和 Interlocked.Decrement(在循环的开始和结束),检查变量中的值是否比之前大,并在Parallel.For完成后输出,像这样:

public void TestParallelism() {
    int maxThreads = 0;
    int currentThreads = 0;

    Parallel.For(0, 100, (i) => {

        var max = Interlocked.Increment(ref currentThreads);

        if (maxThreads < max) {
            maxThreads = max; 
        }

        // your code here...

        Interlocked.Decrement(ref currentThreads);
    });

    Console.WriteLine($ "Max Parallel Threads: {maxThreads}");
}