-
Notifications
You must be signed in to change notification settings - Fork 1
Add ThrottleLock #70
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
Add ThrottleLock #70
Changes from all commits
Commits
Show all changes
9 commits
Select commit
Hold shift + click to select a range
ad2580b
Add ThrottleLock utility with tests
Copilot ef07e8d
Capture DateTimeOffset.Now once to avoid timing inconsistency
Copilot 882e929
Use monotonic Stopwatch timestamp instead of DateTimeOffset
Copilot 77be2ef
Consolidate ThrottleLock tests into 3 focused tests
Copilot f1286d1
Use `is { } last` pattern for nullable long check in ThrottleLock
Copilot b39c0df
Update ThrottleLockTests.cs
Tyrrrz 6f181c3
Simplify WaitAsync_Test: 3 waits, assert >= interval*3; init _lastTim…
Copilot bd58625
Update ThrottleLockTests.cs
Tyrrrz 29359f5
Fix CSharpier formatting: put assertion on single line
Copilot 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,39 @@ | ||
| using System; | ||
| using System.Diagnostics; | ||
| using System.Threading; | ||
| using System.Threading.Tasks; | ||
| using FluentAssertions; | ||
| using PowerKit; | ||
| using Xunit; | ||
|
|
||
| namespace PowerKit.Tests; | ||
|
|
||
| public class ThrottleLockTests | ||
| { | ||
| [Fact] | ||
| public async Task WaitAsync_Test() | ||
|
Tyrrrz marked this conversation as resolved.
|
||
| { | ||
| // Arrange | ||
| using var throttle = new ThrottleLock(TimeSpan.FromMilliseconds(50)); | ||
|
|
||
| // Act | ||
| var stopwatch = Stopwatch.StartNew(); | ||
| await throttle.WaitAsync(); | ||
| await throttle.WaitAsync(); | ||
| await throttle.WaitAsync(); | ||
|
|
||
| // Assert | ||
| stopwatch.Elapsed.Should().BeGreaterThanOrEqualTo(2 * TimeSpan.FromMilliseconds(50)); | ||
| } | ||
|
|
||
| [Fact] | ||
| public async Task WaitAsync_Cancellation_Test() | ||
| { | ||
| // Arrange | ||
| using var throttle = new ThrottleLock(TimeSpan.FromSeconds(10)); | ||
|
|
||
| // Act & assert | ||
| var act = async () => await throttle.WaitAsync(new CancellationToken(true)); | ||
| await act.Should().ThrowAsync<OperationCanceledException>(); | ||
| } | ||
| } | ||
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,48 @@ | ||
| #if NET40_OR_GREATER || NETSTANDARD || NET | ||
| #nullable enable | ||
| using System; | ||
| using System.Diagnostics; | ||
| using System.Diagnostics.CodeAnalysis; | ||
| using System.Threading; | ||
| using System.Threading.Tasks; | ||
|
|
||
| namespace PowerKit; | ||
|
|
||
| /// <summary> | ||
| /// Represents a lock that enforces a minimum interval between consecutive acquisitions, | ||
| /// ensuring that operations do not proceed faster than the specified rate. | ||
| /// </summary> | ||
| #if !POWERKIT_INCLUDE_COVERAGE | ||
| [ExcludeFromCodeCoverage] | ||
| #endif | ||
| internal sealed class ThrottleLock(TimeSpan interval) : IDisposable | ||
| { | ||
| private readonly SemaphoreSlim _semaphore = new(1, 1); | ||
| private long _lastTimestamp = Stopwatch.GetTimestamp(); | ||
|
|
||
| /// <summary> | ||
| /// Asynchronously waits until the throttle interval has elapsed since the last acquisition, | ||
| /// then records the current instant as the new last-request time. | ||
| /// </summary> | ||
| public async Task WaitAsync(CancellationToken cancellationToken = default) | ||
| { | ||
| await _semaphore.WaitAsync(cancellationToken).ConfigureAwait(false); | ||
|
|
||
| try | ||
| { | ||
| var remaining = interval - Stopwatch.GetElapsedTime(_lastTimestamp); | ||
| if (remaining > TimeSpan.Zero) | ||
| await Task.Delay(remaining, cancellationToken).ConfigureAwait(false); | ||
|
|
||
| _lastTimestamp = Stopwatch.GetTimestamp(); | ||
| } | ||
| finally | ||
| { | ||
| _semaphore.Release(); | ||
| } | ||
| } | ||
|
|
||
| /// <inheritdoc /> | ||
| public void Dispose() => _semaphore.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.