-
Notifications
You must be signed in to change notification settings - Fork 74
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Improvements to DispatcherQueueTimer.Debounce extension (#569)
* Add baseline single scenario tests for DispatcherQueueTimer Debounce * Add some DispatcherQueueTimer docs, initial sample, and more unit tests TODO: Still have the opposite scenario of Trailing to leading which is broken to fix. * Add test and fix behavior for when switching Debounce mode from Trailing to Leading for a DispatcherQueueTimer * Add Debounce test for stopping the timer manually * Add mouse clicking debounce sample * Clean-up usage of the sample slider value in the Debounce samples * Switch Debounce DispatcherQueueTimer extension to use ConditionalWeakTable This prevents capture holding onto the timer for garbage collection, validated with a unit test which fails with the ConcurrentDictionary, but succeeds with the ConditionalWeakTable Because of the new Trailing/Leading behavior, we need the table in order to know if something was scheduled, otherwise we'd need reflection if we only stored the event handler, which wouldn't be AOT compatible. * Apply XAML Styler * Add additional notes/details about how to use the DispatcherQueueTimer.Debounce method to the docs * Clarify behavior in docs and test results of registering to the Tick event of the DispatcherQueueTimer when using Debounce Behavior should be well defined now. In the future, we could define a 'repeating' behavior, if we think it'd be useful (not sure of the specific scenario), but to do so, I would recommend we encorporate it at the end of the current signature and make false by default: public static void Debounce(this DispatcherQueueTimer timer, Action action, TimeSpan interval, bool immediate = false, bool repeat = false) I would imagine, this would do something like continually pulse the Action/Tick event but when additional requests are received that it would disrupt that periodic pattern somehow based on the debounce configuration (trailing/leading)? * Apply Arlo's suggestions from code review on Debounce improvements - Thanks! Co-authored-by: Arlo <[email protected]> --------- Co-authored-by: Arlo <[email protected]>
- Loading branch information
1 parent
fa08f10
commit e3cd8ec
Showing
7 changed files
with
521 additions
and
11 deletions.
There are no files selected for viewing
14 changes: 14 additions & 0 deletions
14
components/Extensions/samples/Dispatcher/KeyboardDebounceSample.xaml
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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,14 @@ | ||
<Page x:Class="ExtensionsExperiment.Samples.DispatcherQueueExtensions.KeyboardDebounceSample" | ||
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" | ||
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" | ||
xmlns:d="http://schemas.microsoft.com/expression/blend/2008" | ||
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" | ||
Background="{ThemeResource ApplicationPageBackgroundThemeBrush}" | ||
mc:Ignorable="d"> | ||
|
||
<StackPanel Spacing="8"> | ||
<TextBox PlaceholderText="Type here..." | ||
TextChanged="TextBox_TextChanged" /> | ||
<TextBlock x:Name="ResultText" /> | ||
</StackPanel> | ||
</Page> |
42 changes: 42 additions & 0 deletions
42
components/Extensions/samples/Dispatcher/KeyboardDebounceSample.xaml.cs
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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,42 @@ | ||
// Licensed to the .NET Foundation under one or more agreements. | ||
// The .NET Foundation licenses this file to you under the MIT license. | ||
// See the LICENSE file in the project root for more information. | ||
|
||
using CommunityToolkit.WinUI; | ||
#if WINAPPSDK | ||
using DispatcherQueue = Microsoft.UI.Dispatching.DispatcherQueue; | ||
using DispatcherQueueTimer = Microsoft.UI.Dispatching.DispatcherQueueTimer; | ||
#else | ||
using DispatcherQueue = Windows.System.DispatcherQueue; | ||
using DispatcherQueueTimer = Windows.System.DispatcherQueueTimer; | ||
#endif | ||
|
||
namespace ExtensionsExperiment.Samples.DispatcherQueueExtensions; | ||
|
||
[ToolkitSample(id: nameof(KeyboardDebounceSample), "DispatcherQueueTimer Debounce Keyboard", description: "A sample for showing how to use the DispatcherQueueTimer Debounce extension to smooth keyboard input.")] | ||
[ToolkitSampleNumericOption("Interval", 120, 60, 240)] | ||
public sealed partial class KeyboardDebounceSample : Page | ||
{ | ||
public DispatcherQueueTimer _debounceTimer = DispatcherQueue.GetForCurrentThread().CreateTimer(); | ||
|
||
public KeyboardDebounceSample() | ||
{ | ||
InitializeComponent(); | ||
} | ||
|
||
private void TextBox_TextChanged(object sender, TextChangedEventArgs e) | ||
{ | ||
if (sender is TextBox textBox) | ||
{ | ||
_debounceTimer.Debounce(() => | ||
{ | ||
ResultText.Text = textBox.Text; | ||
}, | ||
//// i.e. if another keyboard press comes in within 120ms of the last, we'll wait before we fire off the request | ||
interval: TimeSpan.FromMilliseconds(Interval), | ||
//// If we're blanking out or the first character type, we'll start filtering immediately instead to appear more responsive. | ||
//// We want to switch back to trailing as the user types more so that we still capture all the input. | ||
immediate: textBox.Text.Length <= 1); | ||
} | ||
} | ||
} |
14 changes: 14 additions & 0 deletions
14
components/Extensions/samples/Dispatcher/MouseDebounceSample.xaml
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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,14 @@ | ||
<Page x:Class="ExtensionsExperiment.Samples.DispatcherQueueExtensions.MouseDebounceSample" | ||
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" | ||
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" | ||
xmlns:d="http://schemas.microsoft.com/expression/blend/2008" | ||
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" | ||
Background="{ThemeResource ApplicationPageBackgroundThemeBrush}" | ||
mc:Ignorable="d"> | ||
|
||
<StackPanel Spacing="8"> | ||
<Button Click="Button_Click" | ||
Content="Click Me" /> | ||
<TextBlock x:Name="ResultText" /> | ||
</StackPanel> | ||
</Page> |
39 changes: 39 additions & 0 deletions
39
components/Extensions/samples/Dispatcher/MouseDebounceSample.xaml.cs
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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,39 @@ | ||
// Licensed to the .NET Foundation under one or more agreements. | ||
// The .NET Foundation licenses this file to you under the MIT license. | ||
// See the LICENSE file in the project root for more information. | ||
|
||
using CommunityToolkit.WinUI; | ||
#if WINAPPSDK | ||
using DispatcherQueue = Microsoft.UI.Dispatching.DispatcherQueue; | ||
using DispatcherQueueTimer = Microsoft.UI.Dispatching.DispatcherQueueTimer; | ||
#else | ||
using DispatcherQueue = Windows.System.DispatcherQueue; | ||
using DispatcherQueueTimer = Windows.System.DispatcherQueueTimer; | ||
#endif | ||
|
||
namespace ExtensionsExperiment.Samples.DispatcherQueueExtensions; | ||
|
||
[ToolkitSample(id: nameof(MouseDebounceSample), "DispatcherQueueTimer Debounce Mouse", description: "A sample for showing how to use the DispatcherQueueTimer Debounce extension to smooth mouse input.")] | ||
[ToolkitSampleNumericOption("Interval", 400, 300, 1000)] | ||
public sealed partial class MouseDebounceSample : Page | ||
{ | ||
public DispatcherQueueTimer _debounceTimer = DispatcherQueue.GetForCurrentThread().CreateTimer(); | ||
|
||
private int _count = 0; | ||
|
||
public MouseDebounceSample() | ||
{ | ||
InitializeComponent(); | ||
} | ||
|
||
private void Button_Click(object sender, RoutedEventArgs e) | ||
{ | ||
_debounceTimer.Debounce(() => | ||
{ | ||
ResultText.Text = $"You hit the button {++_count} times!"; | ||
}, | ||
interval: TimeSpan.FromMilliseconds(Interval), | ||
// By being on the leading edge, we ignore inputs past the first for the duration of the interval | ||
immediate: true); | ||
} | ||
} |
42 changes: 42 additions & 0 deletions
42
components/Extensions/samples/DispatcherQueueTimerExtensions.md
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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,42 @@ | ||
--- | ||
title: DispatcherQueueTimerExtensions | ||
author: michael-hawker | ||
description: Helpers for executing code at specific times on a UI thread through a DispatcherQueue instance with a DispatcherQueueTimer. | ||
keywords: dispatcher, dispatcherqueue, DispatcherHelper, DispatcherQueueExtensions, DispatcherQueueTimer, DispatcherQueueTimerExtensions | ||
dev_langs: | ||
- csharp | ||
category: Extensions | ||
subcategory: Miscellaneous | ||
discussion-id: 0 | ||
issue-id: 0 | ||
icon: Assets/Extensions.png | ||
--- | ||
|
||
The `DispatcherQueueTimerExtensions` static class provides an extension method for [`DispatcherQueueTimer`](https://learn.microsoft.com/windows/windows-app-sdk/api/winrt/microsoft.ui.dispatching.dispatcherqueue) objects that make it easier to execute code on a specific UI thread at a specific time. | ||
|
||
The `DispatcherQueueTimerExtensions` provides a single extension method, `Debounce`. This is a standard technique used to rate-limit input from a user to not overload requests on an underlying service or query elsewhere. | ||
|
||
> [!WARNING] | ||
> You should exclusively use the `DispatcherQueueTimer` instance calling `Debounce` for the purposes of Debouncing one specific action/scenario only and not configure it for other additional uses. | ||
For each scenario that you want to Debounce, you'll want to create a separate `DispatcherQueueTimer` instance to track that specific scenario. For instance, if the below samples were both within your application. You'd need two separate timers to track debouncing both scenarios. One for the keyboard input, and a different one for the mouse input. | ||
|
||
> [!NOTE] | ||
> Using the `Debounce` method will set `DispatcherQueueTimer.IsRepeating` to `false` to ensure proper operation. Do not change this value. | ||
> [!NOTE] | ||
> If additionally registering to the `DispatcherQueueTimer.Tick` event (uncommon), it will be raised in one of two ways: 1. For a trailing debounce, it will be raised alongside the requested Action passed to the Debounce method. 2. For a leading debounce, it will be raised when the cooldown has expired and another call to Debounce would result in running the action. | ||
## Syntax | ||
|
||
It can be used in a number of ways, but most simply like so as a keyboard limiter: | ||
|
||
> [!SAMPLE KeyboardDebounceSample] | ||
Or for preventing multiple inputs from occuring accidentally (e.g. ignoring a double/multi-click): | ||
|
||
> [!SAMPLE MouseDebounceSample] | ||
## Examples | ||
|
||
You can find more examples in the [unit tests](https://github.com/CommunityToolkit/Windows/blob/rel/8.1.240916/components/Extensions/tests/DispatcherQueueTimerExtensionTests.cs). |
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
Oops, something went wrong.