Skip to content

Instantly share code, notes, and snippets.

@ShinNoNoir
Created September 7, 2016 10:17
Show Gist options
  • Save ShinNoNoir/6d6abd668764dc73852692a94ba7a475 to your computer and use it in GitHub Desktop.
Save ShinNoNoir/6d6abd668764dc73852692a94ba7a475 to your computer and use it in GitHub Desktop.
Simple throttle utility
using System;
using System.Collections.Generic;
namespace Utilities
{
public class ThrottleManager
{
static Dictionary<object, DateTime> disabledUntil = new Dictionary<object, DateTime>();
public static bool Throttle(object key, int delay)
{
bool allowedToRun;
var now = DateTime.Now;
DateTime expiry;
if (disabledUntil.TryGetValue(key, out expiry))
{
allowedToRun = now > expiry;
}
else
{
allowedToRun = true;
}
if (allowedToRun == true)
{
disabledUntil[key] = now.AddMilliseconds(delay);
}
return allowedToRun;
}
}
}
/*
// Use case in e.g. event handler:
private void Button_Click(object sender, RoutedEventArgs e)
{
if (ThrottleManager.Throttle("SomeAction", 100))
DoSomeAction();
}
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment