Last active
November 27, 2023 13:17
-
-
Save RickStrahl/0519b678f3294e27891f4d4f0608519a to your computer and use it in GitHub Desktop.
Debouncing events by a timeout using a Dispatcher.
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 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; | |
} | |
} |
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
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