Skip to content

Instantly share code, notes, and snippets.

@kyle-seongwoo-jun
Created May 7, 2020 09:01
Show Gist options
  • Save kyle-seongwoo-jun/d1631d09360f3de9c610a99f6e55771c to your computer and use it in GitHub Desktop.
Save kyle-seongwoo-jun/d1631d09360f3de9c610a99f6e55771c to your computer and use it in GitHub Desktop.
C# Limit running code by time
class Limiter
{
static readonly object _mtx = new object();
readonly TimeSpan _limit;
Action _action;
bool _isWaiting;
bool _requested;
public Limiter(double limit) : this(TimeSpan.FromMilliseconds(limit))
{
}
public Limiter(TimeSpan limit)
{
_limit = limit;
}
public void Do(Action action)
{
lock (_mtx)
{
_action = action;
if (_isWaiting)
{
_requested = true;
return;
}
Action();
}
}
private async void Action()
{
_action();
_isWaiting = true;
await Task.Delay(_limit);
if (!_requested)
{
_isWaiting = false;
return;
}
_requested = false;
Action();
}
}
var limiter = new Limiter(1000);
while (true)
{
limiter.Do(() =>
{
Console.WriteLine(DateTime.Now);
});
}
// 05/07/2020 18:00:35
// 05/07/2020 18:00:36
// 05/07/2020 18:00:37
// 05/07/2020 18:00:38
// 05/07/2020 18:00:39
// 05/07/2020 18:00:40
// 05/07/2020 18:00:41
// 05/07/2020 18:00:42
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment