namespace ZB.MOM.WW.ScadaBridge.DataConnectionLayer.Adapters; /// /// Bounded-parallel execution of a per-item operation. Used where a protocol offers no /// bulk form of a command and the only alternative is N serial round trips — today the /// MxAccess Gateway's supervisory advise, which exists per item only (the worker's /// SubscribeBulk issues plain advises). Pipelining 37,500 tags at a window of 16 /// replaces 37,500 serial round trips with ~2,344 windows. /// /// /// Factored out of the gateway client so the concurrency bound is unit-testable without /// a live MXAccess session. /// /// internal static class BulkPipeline { /// /// Runs for every item with at most /// in flight, preserving result order. A per-item /// fault is captured into that item's result slot via /// rather than aborting the pipeline; cancellation propagates. /// /// Input item type. /// Per-item result type. /// Items to process. /// Maximum operations in flight; values < 1 are treated as 1. /// The per-item operation. /// Maps an item plus its exception onto a result row. /// Cancellation token. /// One result per item, in input order. public static async Task RunAsync( IReadOnlyList items, int maxParallelism, Func> operation, Func onError, CancellationToken ct = default) { var results = new TResult[items.Count]; if (items.Count == 0) return results; // Deliberately NOT disposed: on cancellation Task.WhenAll rethrows while sibling // operations may still be unwinding, and a disposed SemaphoreSlim would turn that // into an ObjectDisposedException. SemaphoreSlim without AvailableWaitHandle holds // no unmanaged resource, so letting it be collected is safe. var gate = new SemaphoreSlim(Math.Max(1, maxParallelism)); var tasks = new Task[items.Count]; for (var i = 0; i < items.Count; i++) { var index = i; var item = items[i]; tasks[i] = RunOneAsync(item, index); } await Task.WhenAll(tasks).ConfigureAwait(false); return results; async Task RunOneAsync(TItem item, int index) { await gate.WaitAsync(ct).ConfigureAwait(false); try { results[index] = await operation(item, ct).ConfigureAwait(false); } catch (OperationCanceledException) { throw; } catch (Exception ex) { results[index] = onError(item, ex); } finally { gate.Release(); } } } }