Skip to content

Commit e3cd8ec

Browse files
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 <arlo.godfrey@outlook.com> --------- Co-authored-by: Arlo <arlo.godfrey@outlook.com>
1 parent fa08f10 commit e3cd8ec

File tree

7 files changed

+521
-11
lines changed

7 files changed

+521
-11
lines changed
Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
<Page x:Class="ExtensionsExperiment.Samples.DispatcherQueueExtensions.KeyboardDebounceSample"
2+
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
3+
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
4+
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
5+
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
6+
Background="{ThemeResource ApplicationPageBackgroundThemeBrush}"
7+
mc:Ignorable="d">
8+
9+
<StackPanel Spacing="8">
10+
<TextBox PlaceholderText="Type here..."
11+
TextChanged="TextBox_TextChanged" />
12+
<TextBlock x:Name="ResultText" />
13+
</StackPanel>
14+
</Page>
Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
// Licensed to the .NET Foundation under one or more agreements.
2+
// The .NET Foundation licenses this file to you under the MIT license.
3+
// See the LICENSE file in the project root for more information.
4+
5+
using CommunityToolkit.WinUI;
6+
#if WINAPPSDK
7+
using DispatcherQueue = Microsoft.UI.Dispatching.DispatcherQueue;
8+
using DispatcherQueueTimer = Microsoft.UI.Dispatching.DispatcherQueueTimer;
9+
#else
10+
using DispatcherQueue = Windows.System.DispatcherQueue;
11+
using DispatcherQueueTimer = Windows.System.DispatcherQueueTimer;
12+
#endif
13+
14+
namespace ExtensionsExperiment.Samples.DispatcherQueueExtensions;
15+
16+
[ToolkitSample(id: nameof(KeyboardDebounceSample), "DispatcherQueueTimer Debounce Keyboard", description: "A sample for showing how to use the DispatcherQueueTimer Debounce extension to smooth keyboard input.")]
17+
[ToolkitSampleNumericOption("Interval", 120, 60, 240)]
18+
public sealed partial class KeyboardDebounceSample : Page
19+
{
20+
public DispatcherQueueTimer _debounceTimer = DispatcherQueue.GetForCurrentThread().CreateTimer();
21+
22+
public KeyboardDebounceSample()
23+
{
24+
InitializeComponent();
25+
}
26+
27+
private void TextBox_TextChanged(object sender, TextChangedEventArgs e)
28+
{
29+
if (sender is TextBox textBox)
30+
{
31+
_debounceTimer.Debounce(() =>
32+
{
33+
ResultText.Text = textBox.Text;
34+
},
35+
//// i.e. if another keyboard press comes in within 120ms of the last, we'll wait before we fire off the request
36+
interval: TimeSpan.FromMilliseconds(Interval),
37+
//// If we're blanking out or the first character type, we'll start filtering immediately instead to appear more responsive.
38+
//// We want to switch back to trailing as the user types more so that we still capture all the input.
39+
immediate: textBox.Text.Length <= 1);
40+
}
41+
}
42+
}
Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
<Page x:Class="ExtensionsExperiment.Samples.DispatcherQueueExtensions.MouseDebounceSample"
2+
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
3+
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
4+
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
5+
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
6+
Background="{ThemeResource ApplicationPageBackgroundThemeBrush}"
7+
mc:Ignorable="d">
8+
9+
<StackPanel Spacing="8">
10+
<Button Click="Button_Click"
11+
Content="Click Me" />
12+
<TextBlock x:Name="ResultText" />
13+
</StackPanel>
14+
</Page>
Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
// Licensed to the .NET Foundation under one or more agreements.
2+
// The .NET Foundation licenses this file to you under the MIT license.
3+
// See the LICENSE file in the project root for more information.
4+
5+
using CommunityToolkit.WinUI;
6+
#if WINAPPSDK
7+
using DispatcherQueue = Microsoft.UI.Dispatching.DispatcherQueue;
8+
using DispatcherQueueTimer = Microsoft.UI.Dispatching.DispatcherQueueTimer;
9+
#else
10+
using DispatcherQueue = Windows.System.DispatcherQueue;
11+
using DispatcherQueueTimer = Windows.System.DispatcherQueueTimer;
12+
#endif
13+
14+
namespace ExtensionsExperiment.Samples.DispatcherQueueExtensions;
15+
16+
[ToolkitSample(id: nameof(MouseDebounceSample), "DispatcherQueueTimer Debounce Mouse", description: "A sample for showing how to use the DispatcherQueueTimer Debounce extension to smooth mouse input.")]
17+
[ToolkitSampleNumericOption("Interval", 400, 300, 1000)]
18+
public sealed partial class MouseDebounceSample : Page
19+
{
20+
public DispatcherQueueTimer _debounceTimer = DispatcherQueue.GetForCurrentThread().CreateTimer();
21+
22+
private int _count = 0;
23+
24+
public MouseDebounceSample()
25+
{
26+
InitializeComponent();
27+
}
28+
29+
private void Button_Click(object sender, RoutedEventArgs e)
30+
{
31+
_debounceTimer.Debounce(() =>
32+
{
33+
ResultText.Text = $"You hit the button {++_count} times!";
34+
},
35+
interval: TimeSpan.FromMilliseconds(Interval),
36+
// By being on the leading edge, we ignore inputs past the first for the duration of the interval
37+
immediate: true);
38+
}
39+
}
Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
---
2+
title: DispatcherQueueTimerExtensions
3+
author: michael-hawker
4+
description: Helpers for executing code at specific times on a UI thread through a DispatcherQueue instance with a DispatcherQueueTimer.
5+
keywords: dispatcher, dispatcherqueue, DispatcherHelper, DispatcherQueueExtensions, DispatcherQueueTimer, DispatcherQueueTimerExtensions
6+
dev_langs:
7+
- csharp
8+
category: Extensions
9+
subcategory: Miscellaneous
10+
discussion-id: 0
11+
issue-id: 0
12+
icon: Assets/Extensions.png
13+
---
14+
15+
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.
16+
17+
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.
18+
19+
> [!WARNING]
20+
> 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.
21+
22+
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.
23+
24+
> [!NOTE]
25+
> Using the `Debounce` method will set `DispatcherQueueTimer.IsRepeating` to `false` to ensure proper operation. Do not change this value.
26+
27+
> [!NOTE]
28+
> 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.
29+
30+
## Syntax
31+
32+
It can be used in a number of ways, but most simply like so as a keyboard limiter:
33+
34+
> [!SAMPLE KeyboardDebounceSample]
35+
36+
Or for preventing multiple inputs from occuring accidentally (e.g. ignoring a double/multi-click):
37+
38+
> [!SAMPLE MouseDebounceSample]
39+
40+
## Examples
41+
42+
You can find more examples in the [unit tests](https://github.com/CommunityToolkit/Windows/blob/rel/8.1.240916/components/Extensions/tests/DispatcherQueueTimerExtensionTests.cs).

components/Extensions/src/Dispatcher/DispatcherQueueTimerExtensions.cs

Lines changed: 22 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,8 @@
33
// See the LICENSE file in the project root for more information.
44

55
using System.Collections.Concurrent;
6+
using System.Runtime.CompilerServices;
7+
68

79
#if WINAPPSDK
810
using DispatcherQueueTimer = Microsoft.UI.Dispatching.DispatcherQueueTimer;
@@ -17,25 +19,26 @@ namespace CommunityToolkit.WinUI;
1719
/// </summary>
1820
public static class DispatcherQueueTimerExtensions
1921
{
20-
private static ConcurrentDictionary<DispatcherQueueTimer, Action> _debounceInstances = new ConcurrentDictionary<DispatcherQueueTimer, Action>();
22+
/// <inheritdoc cref="System.Runtime.CompilerServices.ConditionalWeakTable{TKey,TValue}" />
23+
private static ConditionalWeakTable<DispatcherQueueTimer, Action> _debounceInstances = new();
2124

2225
/// <summary>
23-
/// <para>Used to debounce (rate-limit) an event. The action will be postponed and executed after the interval has elapsed. At the end of the interval, the function will be called with the arguments that were passed most recently to the debounced function.</para>
26+
/// <para>Used to debounce (rate-limit) an event. The action will be postponed and executed after the interval has elapsed. At the end of the interval, the function will be called with the arguments that were passed most recently to the debounced function. Useful for smoothing keyboard input, for instance.</para>
2427
/// <para>Use this method to control the timer instead of calling Start/Interval/Stop manually.</para>
2528
/// <para>A scheduled debounce can still be stopped by calling the stop method on the timer instance.</para>
2629
/// <para>Each timer can only have one debounced function limited at a time.</para>
2730
/// </summary>
2831
/// <param name="timer">Timer instance, only one debounced function can be used per timer.</param>
2932
/// <param name="action">Action to execute at the end of the interval.</param>
3033
/// <param name="interval">Interval to wait before executing the action.</param>
31-
/// <param name="immediate">Determines if the action execute on the leading edge instead of trailing edge.</param>
34+
/// <param name="immediate">Determines if the action execute on the leading edge instead of trailing edge of the interval. Subsequent input will be ignored into the interval has completed. Useful for ignore extraneous extra input like multiple mouse clicks.</param>
3235
/// <example>
3336
/// <code>
3437
/// private DispatcherQueueTimer _typeTimer = DispatcherQueue.GetForCurrentThread().CreateTimer();
3538
///
3639
/// _typeTimer.Debounce(async () =>
3740
/// {
38-
/// // Only executes this code after 0.3 seconds have elapsed since last trigger.
41+
/// // Only executes code put here after 0.3 seconds have elapsed since last call to Debounce.
3942
/// }, TimeSpan.FromSeconds(0.3));
4043
/// </code>
4144
/// </example>
@@ -52,8 +55,20 @@ public static void Debounce(this DispatcherQueueTimer timer, Action action, Time
5255
timer.Tick -= Timer_Tick;
5356
timer.Interval = interval;
5457

58+
// Ensure we haven't been misconfigured and won't execute more times than we expect.
59+
timer.IsRepeating = false;
60+
5561
if (immediate)
5662
{
63+
// If we have a _debounceInstance queued, then we were running in trailing mode,
64+
// so if we now have the immediate flag, we should ignore this timer, and run immediately.
65+
if (_debounceInstances.TryGetValue(timer, out var _))
66+
{
67+
timeout = false;
68+
69+
_debounceInstances.Remove(timer);
70+
}
71+
5772
// If we're in immediate mode then we only execute if the timer wasn't running beforehand
5873
if (!timeout)
5974
{
@@ -66,7 +81,7 @@ public static void Debounce(this DispatcherQueueTimer timer, Action action, Time
6681
timer.Tick += Timer_Tick;
6782

6883
// Store/Update function
69-
_debounceInstances.AddOrUpdate(timer, action, (k, v) => action);
84+
_debounceInstances.AddOrUpdate(timer, action);
7085
}
7186

7287
// Start the timer to keep track of the last call here.
@@ -81,8 +96,9 @@ private static void Timer_Tick(object sender, object e)
8196
timer.Tick -= Timer_Tick;
8297
timer.Stop();
8398

84-
if (_debounceInstances.TryRemove(timer, out Action? action))
99+
if (_debounceInstances.TryGetValue(timer, out Action? action))
85100
{
101+
_debounceInstances.Remove(timer);
86102
action?.Invoke();
87103
}
88104
}

0 commit comments

Comments
 (0)