BulkheadPolicy
A bulkhead-isolation policy which can be applied to delegates.
using System;
using System.Diagnostics;
using System.Runtime.CompilerServices;
using System.Threading;
namespace Polly.Bulkhead
{
[System.Runtime.CompilerServices.NullableContext(1)]
[System.Runtime.CompilerServices.Nullable(0)]
public class BulkheadPolicy : Policy, IBulkheadPolicy, IsPolicy, IDisposable
{
private readonly SemaphoreSlim _maxParallelizationSemaphore;
private readonly SemaphoreSlim _maxQueuedActionsSemaphore;
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, Action<Context> onBulkheadRejected)
: base((PolicyBuilder)null)
{
_maxQueueingActions = maxQueueingActions;
if (onBulkheadRejected == null)
throw new ArgumentNullException("onBulkheadRejected");
_onBulkheadRejected = onBulkheadRejected;
(SemaphoreSlim, SemaphoreSlim) valueTuple = BulkheadSemaphoreFactory.CreateBulkheadSemaphores(maxParallelization, maxQueueingActions);
_maxParallelizationSemaphore = valueTuple.Item1;
_maxQueuedActionsSemaphore = valueTuple.Item2;
}
[DebuggerStepThrough]
protected override TResult Implementation<[System.Runtime.CompilerServices.Nullable(0)] TResult>(Func<Context, CancellationToken, TResult> action, Context context, CancellationToken cancellationToken)
{
if (action == null)
throw new ArgumentNullException("action");
return BulkheadEngine.Implementation(action, context, _onBulkheadRejected, _maxParallelizationSemaphore, _maxQueuedActionsSemaphore, cancellationToken);
}
public void Dispose()
{
_maxParallelizationSemaphore.Dispose();
_maxQueuedActionsSemaphore.Dispose();
GC.SuppressFinalize(this);
}
}
}