<PackageReference Include="Polly" Version="7.1.0" />

BulkheadPolicy

A bulkhead-isolation policy which can be applied to delegates.
using System; using System.Diagnostics; using System.Threading; namespace Polly.Bulkhead { public class BulkheadPolicy : Policy, IBulkheadPolicy, IsPolicy, IDisposable { private readonly SemaphoreSlim _maxParallelizationSemaphore; private readonly SemaphoreSlim _maxQueuedActionsSemaphore; private readonly int _maxParallelization; private readonly int _maxQueueingActions; private readonly Action<Context> _onBulkheadRejected; public int BulkheadAvailableCount => _maxParallelizationSemaphore.CurrentCount; public int QueueAvailableCount => Math.Min(_maxQueuedActionsSemaphore.CurrentCount, _maxQueueingActions); internal BulkheadPolicy(int maxParallelization, int maxQueueingActions, SemaphoreSlim maxParallelizationSemaphore, SemaphoreSlim maxQueuedActionsSemaphore, Action<Context> onBulkheadRejected) : base((PolicyBuilder)null) { _maxParallelization = maxParallelization; _maxQueueingActions = maxQueueingActions; if (maxParallelizationSemaphore == null) throw new ArgumentNullException("maxParallelizationSemaphore"); _maxParallelizationSemaphore = maxParallelizationSemaphore; if (maxQueuedActionsSemaphore == null) throw new ArgumentNullException("maxQueuedActionsSemaphore"); _maxQueuedActionsSemaphore = maxQueuedActionsSemaphore; if (onBulkheadRejected == null) throw new ArgumentNullException("onBulkheadRejected"); _onBulkheadRejected = onBulkheadRejected; } [DebuggerStepThrough] protected override TResult Implementation<TResult>(Func<Context, CancellationToken, TResult> action, Context context, CancellationToken cancellationToken) { return BulkheadEngine.Implementation(action, context, _onBulkheadRejected, _maxParallelizationSemaphore, _maxQueuedActionsSemaphore, cancellationToken); } public void Dispose() { _maxParallelizationSemaphore.Dispose(); _maxQueuedActionsSemaphore.Dispose(); } } }