Repository navigation
[dev-v5] Add Debounce #2656
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Vincent Baaij (vnbaaij)
merged 7 commits into
dev-v5
from
users/dvoituron/dev-v5/debounce
Sep 16, 2024
Merged
[dev-v5] Add Debounce #2656
Changes from all commits
Commits
Show all changes
7 commits
Select commit
Hold shift + click to select a range
40fdbc9
Add new Debounce class
dvoituron cccfbe2
Add Unit Tests
dvoituron a00efd3
Fix Unit Test
dvoituron 41f0e5a
Add Debounce Timer
dvoituron 0248acb
Refactore names
dvoituron 86d8ea4
Fix Task MultipleCalls
dvoituron 360e8dd
Refactoring to create a common class Debounce
dvoituron File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or 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,13 @@ | ||
| // ------------------------------------------------------------------------ | ||
| // MIT License - Copyright (c) Microsoft Corporation. All rights reserved. | ||
| // ------------------------------------------------------------------------ | ||
|
|
||
| namespace Microsoft.FluentUI.AspNetCore.Components.Utilities; | ||
|
|
||
| /// <summary> | ||
| /// The DebounceTask dispatcher delays the invocation of an action until a predetermined interval has elapsed since the last call. | ||
| /// This ensures that the action is only invoked once after the calls have stopped for the specified duration. | ||
| /// </summary> | ||
| public sealed class Debounce : InternalDebounce.DebounceTask | ||
| { | ||
| } |
This file contains hidden or 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,61 @@ | ||
| // ------------------------------------------------------------------------ | ||
| // MIT License - Copyright (c) Microsoft Corporation. All rights reserved. | ||
| // ------------------------------------------------------------------------ | ||
|
|
||
| namespace Microsoft.FluentUI.AspNetCore.Components.Utilities.InternalDebounce; | ||
|
|
||
| /// <summary> | ||
| /// The DebounceTask dispatcher delays the invocation of an action until a predetermined interval has elapsed since the last call. | ||
| /// This ensures that the action is only invoked once after the calls have stopped for the specified duration. | ||
| /// </summary> | ||
| [Obsolete("Use Debounce, which inherits from DebounceTask.")] | ||
| internal class DebounceAction : IDisposable | ||
| { | ||
| private bool _disposed; | ||
| private readonly System.Timers.Timer _timer = new(); | ||
| private TaskCompletionSource? _taskCompletionSource; | ||
|
|
||
| /// <summary> | ||
| /// Gets a value indicating whether the DebounceTask dispatcher is busy. | ||
| /// </summary> | ||
| public bool Busy => _taskCompletionSource?.Task.Status == TaskStatus.Running && !_disposed; | ||
|
|
||
| /// <summary> | ||
| /// Gets the current task. | ||
| /// </summary> | ||
| public Task CurrentTask => _taskCompletionSource?.Task ?? Task.CompletedTask; | ||
|
|
||
| /// <summary> | ||
| /// Delays the invocation of an action until a predetermined interval has elapsed since the last call. | ||
| /// </summary> | ||
| /// <param name="milliseconds"></param> | ||
| /// <param name="action"></param> | ||
| /// <exception cref="ArgumentOutOfRangeException"></exception> | ||
| public void Run(int milliseconds, Func<Task> action) | ||
| { | ||
| // Check arguments | ||
| if (milliseconds <= 0) | ||
| { | ||
| throw new ArgumentOutOfRangeException(nameof(milliseconds), milliseconds, "The milliseconds must be greater than to zero."); | ||
| } | ||
|
|
||
| ArgumentNullException.ThrowIfNull(action); | ||
|
|
||
| // DebounceTask | ||
| if (!_disposed) | ||
| { | ||
| _taskCompletionSource = _timer.Debounce(action, milliseconds); | ||
| } | ||
| } | ||
|
|
||
| /// <summary> | ||
| /// Releases all resources used by the DebounceTask dispatcher. | ||
| /// </summary> | ||
| public void Dispose() | ||
| { | ||
| _taskCompletionSource = null; | ||
| _timer.Dispose(); | ||
| _disposed = true; | ||
| GC.SuppressFinalize(this); | ||
| } | ||
| } | ||
This file contains hidden or 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,84 @@ | ||
| // ------------------------------------------------------------------------ | ||
| // MIT License - Copyright (c) Microsoft Corporation. All rights reserved. | ||
| // ------------------------------------------------------------------------ | ||
|
|
||
| namespace Microsoft.FluentUI.AspNetCore.Components.Utilities.InternalDebounce; | ||
|
|
||
| /// <summary> | ||
| /// The DebounceTask dispatcher delays the invocation of an action until a predetermined interval has elapsed since the last call. | ||
| /// This ensures that the action is only invoked once after the calls have stopped for the specified duration. | ||
| /// </summary> | ||
| public class DebounceTask : IDisposable | ||
| { | ||
| #if NET9_0_OR_GREATER | ||
| private readonly System.Threading.Lock _syncRoot = new(); | ||
| #else | ||
| private readonly object _syncRoot = new(); | ||
| #endif | ||
|
|
||
| private bool _disposed; | ||
| private Task? _task; | ||
| private CancellationTokenSource? _cts; | ||
|
|
||
| /// <summary> | ||
| /// Gets a value indicating whether the DebounceTask dispatcher is busy. | ||
| /// </summary> | ||
| public bool Busy => _task?.Status == TaskStatus.Running && !_disposed; | ||
|
|
||
| /// <summary> | ||
| /// Gets the current task. | ||
| /// </summary> | ||
| public Task CurrentTask => _task ?? Task.CompletedTask; | ||
|
|
||
| /// <summary> | ||
| /// Delays the invocation of an action until a predetermined interval has elapsed since the last call. | ||
| /// </summary> | ||
| /// <param name="milliseconds"></param> | ||
| /// <param name="action"></param> | ||
| /// <exception cref="ArgumentOutOfRangeException"></exception> | ||
| public void Run(int milliseconds, Func<Task> action) | ||
| { | ||
| // Check arguments | ||
| if (milliseconds <= 0) | ||
| { | ||
| throw new ArgumentOutOfRangeException(nameof(milliseconds), milliseconds, "The milliseconds must be greater than to zero."); | ||
| } | ||
|
|
||
| ArgumentNullException.ThrowIfNull(action); | ||
|
|
||
| // Cancel the previous task if it's still running | ||
| _cts?.Cancel(); | ||
|
|
||
| // Create a new cancellation token source | ||
| _cts = new CancellationTokenSource(); | ||
|
|
||
| try | ||
| { | ||
| // Wait for the specified time | ||
| _task = Task.Delay(TimeSpan.FromMilliseconds(milliseconds), _cts.Token) | ||
| .ContinueWith(t => | ||
| { | ||
| if (!_disposed && !_cts.IsCancellationRequested) | ||
| { | ||
| lock (_syncRoot) | ||
| { | ||
| _ = action.Invoke(); | ||
| } | ||
| } | ||
| }, _cts.Token, TaskContinuationOptions.OnlyOnRanToCompletion, TaskScheduler.Current); | ||
| } | ||
| catch (TaskCanceledException) | ||
| { | ||
| // Task was canceled | ||
| } | ||
| } | ||
|
|
||
| /// <summary> | ||
| /// Releases all resources used by the DebounceTask dispatcher. | ||
| /// </summary> | ||
| public void Dispose() | ||
| { | ||
| _disposed = true; | ||
| _cts?.Cancel(); | ||
| } | ||
| } |
102 changes: 102 additions & 0 deletions
102
src/Core/Utilities/InternalDebounce/DispatcherTimerExtensions.cs
This file contains hidden or 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,102 @@ | ||
| // ------------------------------------------------------------------------ | ||
| // MIT License - Copyright (c) Microsoft Corporation. All rights reserved. | ||
| // ------------------------------------------------------------------------ | ||
|
|
||
| using System.Collections.Concurrent; | ||
|
|
||
| namespace Microsoft.FluentUI.AspNetCore.Components.Utilities.InternalDebounce; | ||
|
|
||
| /// <summary> | ||
| /// Extension methods for <see cref="System.Timers.Timer"/>. | ||
| /// </summary> | ||
| /// <remarks> | ||
| /// Inspired from Microsoft.Toolkit.Uwp.UI.DispatcherQueueTimerExtensions | ||
| /// </remarks> | ||
| internal static class DispatcherTimerExtensions | ||
| { | ||
| private static readonly ConcurrentDictionary<System.Timers.Timer, TimerDebounceItem> _debounceInstances = new(); | ||
|
|
||
| /// <summary> | ||
| /// Delays the invocation of an action until a predetermined interval has elapsed since the last call. | ||
| /// </summary> | ||
| /// <param name="timer"></param> | ||
| /// <param name="action"></param> | ||
| /// <param name="interval"></param> | ||
| /// <returns></returns> | ||
| public static TaskCompletionSource Debounce(this System.Timers.Timer timer, Func<Task> action, double interval) | ||
| { | ||
| // Check and stop any existing timer | ||
| timer.Stop(); | ||
|
|
||
| // Reset timer parameters | ||
| timer.Elapsed -= Timer_Elapsed; | ||
| timer.Interval = interval; | ||
|
|
||
| // If we're not in immediate mode, then we'll execute when the current timer expires. | ||
| timer.Elapsed += Timer_Elapsed; | ||
|
|
||
| // Store/Update function | ||
| TimerDebounceItem updateValueFactory(System.Timers.Timer k, TimerDebounceItem v) => v.UpdateAction(action); | ||
| var item = _debounceInstances.AddOrUpdate( | ||
| key: timer, | ||
| addValue: new TimerDebounceItem() | ||
| { | ||
| Status = new TaskCompletionSource(), | ||
| Action = action, | ||
| }, | ||
| updateValueFactory: updateValueFactory); | ||
|
|
||
| // Start the timer to keep track of the last call here. | ||
| timer.Start(); | ||
|
|
||
| return item.Status; | ||
| } | ||
|
|
||
| /// <summary> | ||
| /// Timer elapsed event handler. | ||
| /// </summary> | ||
| /// <param name="sender"></param> | ||
| /// <param name="e"></param> | ||
| private static void Timer_Elapsed(object? sender, System.Timers.ElapsedEventArgs e) | ||
| { | ||
| // This event is only registered/run if we weren't in immediate mode above | ||
| if (sender is System.Timers.Timer timer) | ||
| { | ||
| timer.Elapsed -= Timer_Elapsed; | ||
| timer.Stop(); | ||
|
|
||
| if (_debounceInstances.TryRemove(timer, out var item)) | ||
| { | ||
| _ = (item?.Action.Invoke()); | ||
| item?.Status.SetResult(); | ||
| } | ||
| } | ||
| } | ||
|
|
||
| /// <summary> | ||
| /// Timer debounce item. | ||
| /// </summary> | ||
| private class TimerDebounceItem | ||
| { | ||
| /// <summary> | ||
| /// Gets the task completion source. | ||
| /// </summary> | ||
| public required TaskCompletionSource Status { get; init; } | ||
|
|
||
| /// <summary> | ||
| /// Gets or sets the action to execute. | ||
| /// </summary> | ||
| public required Func<Task> Action { get; set; } | ||
|
|
||
| /// <summary> | ||
| /// Updates the action to execute. | ||
| /// </summary> | ||
| /// <param name="action"></param> | ||
| /// <returns></returns> | ||
| public TimerDebounceItem UpdateAction(Func<Task> action) | ||
| { | ||
| Action = action; | ||
| return this; | ||
| } | ||
| } | ||
| } |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.