Skip to content

Instantly share code, notes, and snippets.

@RickStrahl
Last active November 27, 2023 13:17
Show Gist options
  • Star 5 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save RickStrahl/0519b678f3294e27891f4d4f0608519a to your computer and use it in GitHub Desktop.
Save RickStrahl/0519b678f3294e27891f4d4f0608519a to your computer and use it in GitHub Desktop.
Debouncing events by a timeout using a Dispatcher.
public class DebounceDispatcher
{
private DispatcherTimer timer;
public void Debounce(int timeout, Action<object> action,
object param = null,
DispatcherPriority priority = DispatcherPriority.ApplicationIdle,
Dispatcher disp = null)
{
if (disp == null)
disp = Dispatcher.CurrentDispatcher;
if (timer == null)
{
timer = new DispatcherTimer(TimeSpan.FromMilliseconds(timeout), priority, (s, e) =>
{
timer.IsEnabled = false;
action.Invoke(param);
}, disp)
{IsEnabled = true};
}
else
timer.IsEnabled = false;
timer.IsEnabled = true;
}
}
private DebounceDispatcher debounceTimer = new DebounceDispatcher();
private void TextSearchText_KeyUp(object sender, KeyEventArgs e)
{
// only fire after 300ms after last keypress
debounceTimer.Debounce(300, (p) =>
{
Model.AppModel.Window.ShowStatus("Searching topics...");
Model.TopicsFilter = TextSearchText.Text;
Model.AppModel.Window.ShowStatus();
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment