Skip to content

Instantly share code, notes, and snippets.

@VisualBean
Last active January 29, 2021 09:39
Show Gist options
  • Save VisualBean/ac5e4f874a1732644ee90c77ef6c86b8 to your computer and use it in GitHub Desktop.
Save VisualBean/ac5e4f874a1732644ee90c77ef6c86b8 to your computer and use it in GitHub Desktop.
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