Last active
August 29, 2015 14:13
-
-
Save eouw0o83hf/7dfa97a5e08d245d0538 to your computer and use it in GitHub Desktop.
Throttle Helper
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 Throttle | |
{ | |
private Task _control; | |
private readonly int _minimumMillis; | |
public Throttle(int millis) | |
{ | |
_minimumMillis = millis; | |
} | |
public void Block() | |
{ | |
// Only block if it's not the first time | |
if(_control != null) | |
{ | |
_control.Wait(); | |
} | |
_control = Task.Delay(_minimumMillis); | |
} | |
} | |
public static class ThrottleExtensions | |
{ | |
public static IEnumerable<T> Throttled<T>(this IEnumerable<T> source, int millis) | |
{ | |
var throttle = new Throttle(millis); | |
foreach(var item in source) | |
{ | |
throttle.Block(); | |
yield return item; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment