C# Basic Throttle

Date: 2022-06-17
public class Throttle
{
    public Throttler(TimeSpan throttleTime) { ThrottleTime = throttleTime; }
    private DateTime? Last = null;
    private readonly TimeSpan ThrottleTime;
    private readonly object Locker = new();
    public DateTime? LastUsed() => Last ?? DateTime.Now;
    public void Update() => Last = DateTime.Now;
    public bool CanFire()
    {
        lock(Locker) 
        { 
            bool canFire = Last == null || (DateTime.Now - Last).Value > ThrottleTime;
            if (canFire) Update();
            return canFire;
        }
    }
}


// Usage:
public Throttle PopupOpenThrottle = new Throttle(TimeSpan.FromSeconds(1));

private void LeVariant_PopupClosing(object sender, ClosingPopupEventArgs e)
{
	PopupOpenThrottle.Update();
}

private void LeVariant_GotFocus(object sender, RoutedEventArgs e)
{
	if (sender is VariantEditor editor) {
		if (!editor.IsPopupOpen && PopupOpenThrottle.CanFire())
		{ 
			editor.ShowPopup();
		}
	}
}


public class ThrottleDictionary
{
    public ThrottleDictionary(TimeSpan throttleTime) 
    {
        this.throttleTime = throttleTime;
    }
    private readonly Dictionary<string, Throttle> keyValuePairs = new Dictionary<string, Throttle>();
    private readonly TimeSpan throttleTime;

    public Throttle Get(string key) => keyValuePairs.GetOrAdd(key, () => new Throttle(throttleTime));
}
63240cookie-checkC# Basic Throttle