Code/AutoRig/Dl/Concurrency.cs

A small concurrency abstraction that provides a For method replacing Parallel.For. By default it runs a sequential for-loop so it is whitelist-safe in sandboxed Code/. Hosts that are allowed to use Parallel.For can replace Concurrency.ForRunner at startup to use parallel execution.

namespace AutoRig.Dl;

/// <summary>
/// Whitelist-safe parallelism seam. s&amp;box's whitelist does NOT allow
/// System.Threading.Tasks.Parallel inside Code/, so the default runner here is
/// a plain sequential loop (always legal, everywhere). Unwhitelisted hosts —
/// the editor (DlModelRegistry/AutoRigWindow) and the dev test rig — swap in
/// real Parallel.For at startup, which is where the heavy inference actually
/// runs. Inference code must call <see cref="For"/> instead of Parallel.For.
/// </summary>
public static class Concurrency
{
    /// <summary>(fromInclusive, toExclusive, body). Replace to parallelize.</summary>
    public static Action<int, int, Action<int>> ForRunner { get; set; } =
        static ( from, to, body ) =>
        {
            for ( var i = from; i < to; i++ )
                body( i );
        };

    public static void For( int fromInclusive, int toExclusive, Action<int> body )
        => ForRunner( fromInclusive, toExclusive, body );
}