Last active
January 29, 2021 09:39
-
-
Save VisualBean/ac5e4f874a1732644ee90c77ef6c86b8 to your computer and use it in GitHub Desktop.
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
public class Collapser<TResult> | |
{ | |
private SemaphoreSlim semaphore = new SemaphoreSlim(1, 1); | |
private long windowInTicks; | |
private long nextRun; | |
private TResult lastResult; | |
public Collapser(TimeSpan window) | |
{ | |
this.windowInTicks = window.Ticks; | |
} | |
public async Task<TResult> ExecuteAsync(Func<CancellationToken, Task<TResult>> innerAction, CancellationToken cancellationToken) | |
{ | |
long requestStart = DateTime.UtcNow.Ticks; | |
try | |
{ | |
await semaphore.WaitAsync(); | |
if (requestStart <= nextRun) | |
{ | |
return this.lastResult; | |
} | |
this.lastResult = await innerAction(cancellationToken); | |
this.nextRun = requestStart + windowInTicks; | |
return lastResult; | |
} | |
finally | |
{ | |
semaphore.Release(); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment