[Novice] – Debounce Class with System.Timers.Timer only

Hi,

I tried to code some debounce class for personal project and i would really appreciate if you can make me some feedbacks.

Bye.

(Sorry for my english)

public class DebounceDispatcher<T> { private double _i; private ConcurrentDictionary<T, Value> _d = new ConcurrentDictionary<T, Value>(); public DebounceDispatcher(double interval) { _i = interval; } public void Debounce(T key, Action a) { Value t; if (RestartTimer(key, a)) { return; } t = new Value { Timer = new System.Timers.Timer(_i), Action = a}; t.Timer.Elapsed += (s, e) => { t.Action.Invoke(); t.Timer.Stop(); t.Timer.Dispose(); Value v; _d.TryRemove(key, out v); }; if (_d.TryAdd(key, t)) { t.Timer.Start(); } else { if (!RestartTimer(key, a)) { throw new Exception("Cannot add items or remove"); } } } private bool RestartTimer(T key, Action a) { Value t; if (_d.TryGetValue(key, out t)) { t.Timer.Stop(); t.Action = a; t.Timer.Start(); return true; } else { return false; } } private class Value { public System.Timers.Timer Timer { get; set; } public Action Action { get; set; } } } 

submitted by /u/Kimbeauxaaaa
[link] [comments]

Leave a Reply