public bool TryReenter(ReentryMode reentryMode) { if (reentryMode == ReentryMode.CheckedFail) { if (Count > 0) { throw Errors.AlreadyLocked(); } return(false); } var spinWait = new SpinWait(); var count = Count; while (count > 0) { var oldCount = Interlocked.CompareExchange(ref _count, count + 1, count); if (oldCount == count) { return(true); } count = oldCount; spinWait.SpinOnce(); } return(false); }
public AsyncLock(ReentryMode reentryMode, TaskCreationOptions taskCreationOptions = TaskCreationOptions.RunContinuationsAsynchronously) { ReentryMode = reentryMode; _taskCreationOptions = taskCreationOptions; _reentryCounter = ReentryMode != ReentryMode.UncheckedDeadlock ? new AsyncLocal <ReentryCounter>() : null; }
public AsyncLockSet( ReentryMode reentryMode, TaskCreationOptions taskCreationOptions, int concurrencyLevel, int capacity) { ReentryMode = reentryMode; _entries = new ConcurrentDictionary <TKey, Entry>(concurrencyLevel, capacity); _lockPool = new ConcurrentPool <AsyncLock>( () => new AsyncLock(ReentryMode, taskCreationOptions)); }
public int Enter(ReentryMode reentryMode) { if (reentryMode != ReentryMode.CheckedFail) { return(Interlocked.Increment(ref _count)); } if (0 != Interlocked.CompareExchange(ref _count, 1, 0)) { throw Errors.AlreadyLocked(); } return(1); }
public SharedResourcePool( Func <TKey, CancellationToken, ValueTask <TResource?> > resourceFactory, Func <TKey, TResource, ValueTask> resourceDisposer, Func <TKey, TResource, CancellationToken, ValueTask>?resourceDisposeDelayer = null, ReentryMode lockReentryMode = ReentryMode.UncheckedDeadlock, bool useConcurrentDispose = false) : base(lockReentryMode, useConcurrentDispose) { _resourceFactory = resourceFactory; _resourceDisposer = resourceDisposer; _resourceDisposeDelayer = resourceDisposeDelayer ?? ((key, resource, cancellationToken) => ValueTaskEx.CompletedTask); // No delay }
protected override IAsyncLock CreateAsyncLock(ReentryMode reentryMode) { var key = RandomStringGenerator.Default.Next(); switch (reentryMode) { case ReentryMode.CheckedFail: return(new AsyncSetLock <string>(CheckedFailSet, key)); case ReentryMode.CheckedPass: return(new AsyncSetLock <string>(CheckedPassSet, key)); case ReentryMode.UncheckedDeadlock: return(new AsyncSetLock <string>(UncheckedDeadlockSet, key)); default: throw new ArgumentOutOfRangeException(nameof(reentryMode), reentryMode, null); } }
protected override IAsyncLock CreateAsyncLock(ReentryMode reentryMode) => new AsyncLock(reentryMode);
public AsyncLockSet( ReentryMode reentryMode, TaskCreationOptions taskCreationOptions = TaskCreationOptions.RunContinuationsAsynchronously) : this(reentryMode, taskCreationOptions, DefaultConcurrencyLevel, DefaultCapacity) { }