使用 Parallel.Foreach 中的 ParallelOptions 在串行和并行操作之间切换

Using ParallelOptions in Parallel.Foreach for toggling between Serial and Parallel operations

我们在代码中广泛使用了Parallel.Foreach,我们唯一的挑战是如何在调试模式下使用可视化调试时使其串行化,以下是我们正在做的事情,请分享您的看法:

public static class ParallelOptionsWrapper
{
    // Private instance of ParallelOptions 
    private static readonly ParallelOptions @ParallelOptions;

    // Private constructor
    static ParallelOptionsWrapper()
    {
        @ParallelOptions = new ParallelOptions();

#if DEBUG
        // 1 is sequential
        @ParallelOptions.MaxDegreeOfParallelism = 1;
#else
        // -1 is unlimited
        @ParallelOptions.MaxDegreeOfParallelism = -1;
#endif
    }

    public static ParallelOptions Instance() { return @ParallelOptions; }
}

用法如下:

Parallel.ForEach(EnumerableList, ParallelOptionsWrapper.Instance(), element =>
{
// Code to run in Parallel
}

在这种情况下,所有 Parallel.Foreach 调用都具有相同的 ParallelOptions 实例,在我看来应该没问题。

这里安全吗?这样有效率吗?

Is it safe?

是的。只要你不使用取消。

Is this efficient?

只不过是使用单独的实例(即删除所有 static 东西)。
所以这是可以接受的边界,但肯定不是一个好的做法。

您只需要:

public static ParallelOptions StandardParallelOptions() 
{
        otions = new ParallelOptions();    
#if DEBUG
        // 1 is sequential
        options.MaxDegreeOfParallelism = 1;
#else
        // -1 is unlimited
        options.MaxDegreeOfParallelism = -1;
#endif
       return options;   // separate instance for each loop
}

这将允许设置 CancellationToken 等。