-
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 all commits
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
Some comments aren't visible on the classic Files Changed page.
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,54 @@ | ||
| 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_Test() | ||
| { | ||
| // Arrange | ||
| using var semaphore = new ResizableSemaphore { MaxCount = 1 }; | ||
|
|
||
| // Act | ||
| using var access1 = await semaphore.AcquireAsync(); | ||
| var access2Task = semaphore.AcquireAsync(); | ||
|
|
||
| // Assert | ||
| access2Task.IsCompleted.Should().BeFalse(); | ||
| access1.Dispose(); | ||
| using var access2 = await access2Task; | ||
| } | ||
|
|
||
| [Fact] | ||
| public async Task AcquireAsync_Cancellation_Test() | ||
| { | ||
| // Arrange | ||
| using var semaphore = new ResizableSemaphore { MaxCount = 1 }; | ||
| using var _ = await semaphore.AcquireAsync(); | ||
|
|
||
| // Act & assert | ||
| var act = async () => await semaphore.AcquireAsync(new CancellationToken(true)); | ||
| await act.Should().ThrowAsync<OperationCanceledException>(); | ||
| } | ||
|
|
||
|
Tyrrrz marked this conversation as resolved.
|
||
| [Fact] | ||
| public async Task AcquireAsync_Resized_Test() | ||
| { | ||
| // Arrange | ||
| using var semaphore = new ResizableSemaphore { MaxCount = 1 }; | ||
| using var _ = await semaphore.AcquireAsync(); | ||
|
|
||
| // Act | ||
| var accessTask = semaphore.AcquireAsync(); | ||
| semaphore.MaxCount = 2; | ||
|
|
||
| // Assert | ||
| using var access = await accessTask; | ||
| } | ||
| } | ||
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,102 @@ | ||
| #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; | ||
|
|
||
| /// <summary> | ||
| /// Semaphore whose maximum concurrency count can be adjusted at run time. | ||
| /// </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 _count; | ||
|
|
||
| /// <summary> | ||
| /// Gets or sets the maximum number of concurrent accesses. | ||
| /// Defaults to <see cref="int.MaxValue" />. | ||
| /// </summary> | ||
| public int MaxCount | ||
| { | ||
| get => field; | ||
| set | ||
| { | ||
| using (_lock.EnterScope()) | ||
| field = value; | ||
|
|
||
| Refresh(); | ||
| } | ||
| } = int.MaxValue; | ||
|
|
||
| private void Refresh() | ||
| { | ||
| using (_lock.EnterScope()) | ||
| { | ||
| // 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() == true) | ||
| _count++; | ||
| } | ||
| } | ||
|
Tyrrrz marked this conversation as resolved.
|
||
| } | ||
|
|
||
| private void Release() | ||
| { | ||
| using (_lock.EnterScope()) | ||
| _count--; | ||
|
|
||
| Refresh(); | ||
| } | ||
|
|
||
| /// <summary> | ||
| /// Acquires access to the semaphore, waiting asynchronously if the maximum concurrency count | ||
| /// has been reached. Dispose the returned handle to release access. | ||
| /// </summary> | ||
| public async Task<IDisposable> AcquireAsync(CancellationToken cancellationToken = default) | ||
| { | ||
| var waiter = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); | ||
|
|
||
| using (_cts.Token.Register(() => waiter.TrySetCanceled(_cts.Token))) | ||
| using (cancellationToken.Register(() => waiter.TrySetCanceled(cancellationToken))) | ||
| using (_lock.EnterScope()) | ||
| { | ||
| ObjectDisposedException.ThrowIf(_isDisposed, this); | ||
| _waiters.Enqueue(waiter); | ||
| } | ||
|
|
||
| Refresh(); | ||
| await waiter.Task.ConfigureAwait(false); | ||
|
|
||
| return Disposable.Create(Release); | ||
| } | ||
|
|
||
| /// <inheritdoc /> | ||
| public void Dispose() | ||
| { | ||
| using (_lock.EnterScope()) | ||
| { | ||
| if (_isDisposed) | ||
| return; | ||
|
|
||
| _isDisposed = true; | ||
| _cts.Cancel(); | ||
| } | ||
|
|
||
| _cts.Dispose(); | ||
| } | ||
| } | ||
| #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.