forked from nozzlegear/ShopifySharp
-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Using a fifo semaphore to ensure that requests are granted access to …
…the API in fifo order.
- Loading branch information
1 parent
e01f23d
commit 32758ff
Showing
2 changed files
with
40 additions
and
3 deletions.
There are no files selected for viewing
37 changes: 37 additions & 0 deletions
37
ShopifySharp/Infrastructure/Policies/LeakyBucketPolicy/FifoSemaphore.cs
This file contains 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,37 @@ | ||
using System.Collections.Concurrent; | ||
using System.Threading; | ||
using System.Threading.Tasks; | ||
|
||
namespace ShopifySharp | ||
{ | ||
internal class FifoSemaphore | ||
{ | ||
private SemaphoreSlim _semaphore; | ||
|
||
private ConcurrentQueue<TaskCompletionSource<bool>> queue = new (); | ||
|
||
public int QueueCount => queue.Count; | ||
|
||
public FifoSemaphore(int initialCount, int maxConcurrency) | ||
{ | ||
_semaphore = new SemaphoreSlim(initialCount, maxConcurrency); | ||
} | ||
|
||
public Task WaitAsync(CancellationToken cancellationToken = default) | ||
{ | ||
var tcs = new TaskCompletionSource<bool>(); | ||
queue.Enqueue(tcs); | ||
_semaphore.WaitAsync(cancellationToken).ContinueWith(t => | ||
{ | ||
if (queue.TryDequeue(out var popped)) | ||
popped.SetResult(true); | ||
}); | ||
return tcs.Task; | ||
} | ||
|
||
public void Release() | ||
{ | ||
_semaphore.Release(); | ||
} | ||
} | ||
} |
This file contains 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