-
Notifications
You must be signed in to change notification settings - Fork 1
Add ResizableSemaphore #71
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from 1 commit
Commits
Show all changes
12 commits
Select commit
Hold shift + click to select a range
f37203c
Add ResizableSemaphore utility with tests
Copilot dfc7d64
Consolidate ResizableSemaphore tests from 8 to 4
Copilot abfff4b
Address ResizableSemaphore review comments
Copilot 469a74b
Use ObjectDisposedException.ThrowIf; remove Dispose_Test
Copilot c18e88d
Synchronize AcquireAsync and Dispose under _lock to fix disposal race
Copilot 61858c0
Merge remote-tracking branch 'origin/prime' into copilot/add-resizabl…
Copilot 96ea716
Merge prime and rewrite ResizableSemaphoreTests to match ThrottleLock…
Copilot 11d7365
Update ResizableSemaphore.cs
Tyrrrz 6f2da41
Update ResizableSemaphoreTests.cs
Tyrrrz 754eef6
Update ResizableSemaphore.cs
Tyrrrz 1a5d6a5
Fix CSharpier formatting and restore null-forgiving ! in Refresh
Copilot da409cf
Update ResizableSemaphore.cs
Tyrrrz File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,139 @@ | ||
| using System; | ||
| using System.Threading; | ||
| using System.Threading.Tasks; | ||
| using FluentAssertions; | ||
| using PowerKit; | ||
| using Xunit; | ||
|
|
||
| namespace PowerKit.Tests; | ||
|
|
||
| public class ResizableSemaphoreTests | ||
| { | ||
| [Fact] | ||
| public async Task AcquireAsync_WithinMaxCount_Test() | ||
| { | ||
| // Arrange | ||
| using var semaphore = new ResizableSemaphore { MaxCount = 2 }; | ||
|
|
||
| // Act | ||
| using var access1 = await semaphore.AcquireAsync(); | ||
| using var access2 = await semaphore.AcquireAsync(); | ||
|
|
||
| // Assert | ||
| access1.Should().NotBeNull(); | ||
| access2.Should().NotBeNull(); | ||
| } | ||
|
|
||
| [Fact] | ||
| public async Task AcquireAsync_BlocksWhenMaxCountReached_Test() | ||
| { | ||
| // Arrange | ||
| using var semaphore = new ResizableSemaphore { MaxCount = 1 }; | ||
| using var access1 = await semaphore.AcquireAsync(); | ||
|
|
||
| // Act | ||
| var acquireTask = semaphore.AcquireAsync(); | ||
|
|
||
| // Assert | ||
| acquireTask.IsCompleted.Should().BeFalse(); | ||
|
|
||
| // Release and let the second acquire complete | ||
| access1.Dispose(); | ||
| using var access2 = await acquireTask; | ||
| access2.Should().NotBeNull(); | ||
| } | ||
|
|
||
| [Fact] | ||
| public async Task AcquireAsync_CancellationToken_Test() | ||
| { | ||
| // Arrange | ||
| using var semaphore = new ResizableSemaphore { MaxCount = 1 }; | ||
| using var access = await semaphore.AcquireAsync(); | ||
| using var cts = new CancellationTokenSource(); | ||
|
|
||
| // Act | ||
| var acquireTask = semaphore.AcquireAsync(cts.Token); | ||
| cts.Cancel(); | ||
|
|
||
| // Assert | ||
| await acquireTask.Awaiting(t => t).Should().ThrowAsync<OperationCanceledException>(); | ||
| } | ||
|
|
||
|
Tyrrrz marked this conversation as resolved.
|
||
| [Fact] | ||
| public async Task AcquireAsync_Dispose_CancelsWaiters_Test() | ||
| { | ||
| // Arrange | ||
| using var semaphore = new ResizableSemaphore { MaxCount = 1 }; | ||
| using var access = await semaphore.AcquireAsync(); | ||
|
|
||
| // Act | ||
| var acquireTask = semaphore.AcquireAsync(); | ||
| semaphore.Dispose(); | ||
|
|
||
| // Assert | ||
| await acquireTask.Awaiting(t => t).Should().ThrowAsync<OperationCanceledException>(); | ||
| } | ||
|
|
||
| [Fact] | ||
| public async Task AcquireAsync_AfterDispose_Throws_Test() | ||
| { | ||
| // Arrange | ||
| using var semaphore = new ResizableSemaphore(); | ||
| semaphore.Dispose(); | ||
|
|
||
| // Act & assert | ||
| await semaphore | ||
| .Awaiting(s => s.AcquireAsync()) | ||
| .Should() | ||
| .ThrowAsync<ObjectDisposedException>(); | ||
| } | ||
|
|
||
| [Fact] | ||
| public async Task MaxCount_IncreasedUnblocksWaiters_Test() | ||
| { | ||
| // Arrange | ||
| using var semaphore = new ResizableSemaphore { MaxCount = 1 }; | ||
| using var access1 = await semaphore.AcquireAsync(); | ||
|
|
||
| // Act | ||
| var acquireTask = semaphore.AcquireAsync(); | ||
| semaphore.MaxCount = 2; | ||
|
|
||
| // Assert | ||
| using var access2 = await acquireTask; | ||
| access2.Should().NotBeNull(); | ||
| } | ||
|
|
||
| [Fact] | ||
| public async Task Release_AllowsNextWaiter_Test() | ||
| { | ||
| // Arrange | ||
| using var semaphore = new ResizableSemaphore { MaxCount = 1 }; | ||
|
|
||
| // Act | ||
| var access1 = await semaphore.AcquireAsync(); | ||
| var acquireTask = semaphore.AcquireAsync(); | ||
|
|
||
| access1.Dispose(); | ||
|
|
||
| // Assert | ||
| using var access2 = await acquireTask; | ||
| access2.Should().NotBeNull(); | ||
| } | ||
|
|
||
| [Fact] | ||
| public async Task Release_DoubleDispose_OnlyReleasesOnce_Test() | ||
| { | ||
| // Arrange | ||
| using var semaphore = new ResizableSemaphore { MaxCount = 1 }; | ||
| var access = await semaphore.AcquireAsync(); | ||
|
|
||
| // Act | ||
| access.Dispose(); | ||
| access.Dispose(); | ||
|
|
||
| // Assert: should still be able to acquire once (count wasn't double-decremented) | ||
| using var access2 = await semaphore.AcquireAsync(); | ||
| access2.Should().NotBeNull(); | ||
| } | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,129 @@ | ||
| #if NET40_OR_GREATER || NETSTANDARD || NET | ||
| #nullable enable | ||
| using System; | ||
| using System.Collections.Generic; | ||
| using System.Diagnostics.CodeAnalysis; | ||
| using System.Threading; | ||
| using System.Threading.Tasks; | ||
|
|
||
| namespace PowerKit; | ||
|
|
||
| #if !POWERKIT_INCLUDE_COVERAGE | ||
| [ExcludeFromCodeCoverage] | ||
| #endif | ||
| file class ResizableSemaphoreAccess(ResizableSemaphore semaphore) : IDisposable | ||
| { | ||
| private bool _isDisposed; | ||
|
|
||
| public void Dispose() | ||
| { | ||
| if (!_isDisposed) | ||
| { | ||
| semaphore.Release(); | ||
| } | ||
|
|
||
| _isDisposed = true; | ||
|
Tyrrrz marked this conversation as resolved.
Outdated
|
||
| } | ||
| } | ||
|
Tyrrrz marked this conversation as resolved.
Outdated
|
||
|
|
||
| /// <summary> | ||
| /// Like a regular semaphore, but the max count can be changed at any point. | ||
|
Tyrrrz marked this conversation as resolved.
Outdated
|
||
| /// </summary> | ||
| #if !POWERKIT_INCLUDE_COVERAGE | ||
| [ExcludeFromCodeCoverage] | ||
| #endif | ||
| internal class ResizableSemaphore : IDisposable | ||
| { | ||
| private readonly Lock _lock = new(); | ||
| private readonly Queue<TaskCompletionSource> _waiters = new(); | ||
| private readonly CancellationTokenSource _cts = new(); | ||
|
|
||
| private bool _isDisposed; | ||
| private int _maxCount = int.MaxValue; | ||
|
Tyrrrz marked this conversation as resolved.
Outdated
|
||
| private int _count; | ||
|
|
||
| /// <summary> | ||
| /// Gets or sets the maximum number of concurrent accesses. | ||
| /// Defaults to <see cref="int.MaxValue" />. | ||
| /// </summary> | ||
| public int MaxCount | ||
| { | ||
| get | ||
| { | ||
| using (_lock.EnterScope()) | ||
| { | ||
| return _maxCount; | ||
| } | ||
| } | ||
| set | ||
| { | ||
| using (_lock.EnterScope()) | ||
| { | ||
| _maxCount = value; | ||
| Refresh(); | ||
| } | ||
| } | ||
|
Tyrrrz marked this conversation as resolved.
|
||
| } | ||
|
|
||
| // Must be called while holding the lock. | ||
|
Tyrrrz marked this conversation as resolved.
Outdated
|
||
| private void Refresh() | ||
| { | ||
| // Provide access to pending waiters, as long as max count allows. | ||
| while (_count < _maxCount && _waiters.TryDequeue(out var waiter)) | ||
| { | ||
| // Don't increment the count if the waiter has already been | ||
| // completed before (most likely by getting canceled). | ||
| if (waiter!.TrySetResult()) | ||
|
Tyrrrz marked this conversation as resolved.
Outdated
|
||
| _count++; | ||
| } | ||
| } | ||
|
|
||
| /// <summary> | ||
| /// Acquires access to the semaphore, waiting asynchronously if the max count has been reached. | ||
| /// Dispose the returned handle to release access. | ||
| /// </summary> | ||
| public async Task<IDisposable> AcquireAsync(CancellationToken cancellationToken = default) | ||
| { | ||
| if (_isDisposed) | ||
| throw new ObjectDisposedException(GetType().Name); | ||
|
Tyrrrz marked this conversation as resolved.
Outdated
|
||
|
|
||
| var waiter = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); | ||
|
|
||
| using var ctsRegistration = _cts.Token.Register(() => waiter.TrySetCanceled(_cts.Token)); | ||
| using var ctRegistration = cancellationToken.Register(() => | ||
| waiter.TrySetCanceled(cancellationToken) | ||
| ); | ||
|
|
||
| using (_lock.EnterScope()) | ||
| { | ||
| _waiters.Enqueue(waiter); | ||
| Refresh(); | ||
| } | ||
|
Tyrrrz marked this conversation as resolved.
|
||
|
|
||
| await waiter.Task.ConfigureAwait(false); | ||
|
|
||
| return new ResizableSemaphoreAccess(this); | ||
| } | ||
|
|
||
| internal void Release() | ||
| { | ||
| using (_lock.EnterScope()) | ||
| { | ||
| _count--; | ||
| Refresh(); | ||
| } | ||
| } | ||
|
|
||
| /// <inheritdoc /> | ||
| public void Dispose() | ||
| { | ||
| if (!_isDisposed) | ||
| { | ||
| _cts.Cancel(); | ||
| _cts.Dispose(); | ||
| } | ||
|
|
||
| _isDisposed = true; | ||
| } | ||
| } | ||
| #endif | ||
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.