Created
September 7, 2016 10:17
-
-
Save ShinNoNoir/6d6abd668764dc73852692a94ba7a475 to your computer and use it in GitHub Desktop.
Simple throttle utility
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
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