From 40fdbc9070ac52637ed2202e3d43d0d4e97007b9 Mon Sep 17 00:00:00 2001 From: Denis Voituron Date: Fri, 13 Sep 2024 18:43:52 +0200 Subject: [PATCH 1/7] Add new Debounce class --- src/Core/Utilities/Debounce.cs | 143 ++++++++++++++++++++++++++ tests/Core/Utilities/DebounceTests.cs | 134 ++++++++++++++++++++++++ 2 files changed, 277 insertions(+) create mode 100644 src/Core/Utilities/Debounce.cs create mode 100644 tests/Core/Utilities/DebounceTests.cs diff --git a/src/Core/Utilities/Debounce.cs b/src/Core/Utilities/Debounce.cs new file mode 100644 index 0000000000..dc46c3dc81 --- /dev/null +++ b/src/Core/Utilities/Debounce.cs @@ -0,0 +1,143 @@ +// ------------------------------------------------------------------------ +// MIT License - Copyright (c) Microsoft Corporation. All rights reserved. +// ------------------------------------------------------------------------ + +namespace Microsoft.FluentUI.AspNetCore.Components.Utilities; + +/// +/// The Debounce 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. +/// +internal sealed class Debounce : IDisposable +{ + // https://learn.microsoft.com/en-us/dotnet/standard/threading/timers + +#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 = new(); + + /// + /// Gets a value indicating whether the Debounce dispatcher is busy. + /// + public bool Busy => _task?.Status == TaskStatus.Running && !_disposed; + + public void Run(int milliseconds, Func 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 => + { + lock (_syncRoot) + { + if (!_disposed && !_cts.IsCancellationRequested) + { + _ = action.Invoke(); + } + } + }, _cts.Token, TaskContinuationOptions.OnlyOnRanToCompletion, TaskScheduler.Current); + + } + catch (TaskCanceledException) + { + // Task was canceled + } + } + + public Task CurrentTask => _task ?? Task.CompletedTask; + + /* + /// + /// Delays the invocation of an action until a predetermined interval has elapsed since the last call. + /// + /// The interval to wait before invoking the action. + /// An action to be invoked after the interval has elapsed. + /// + [System.Diagnostics.CodeAnalysis.SuppressMessage("Usage", "MA0004:Use Task.ConfigureAwait", Justification = "XXX")] +#pragma warning disable CS1998 // Async method lacks 'await' operators and will run synchronously + public async Task DebounceAsync(TimeSpan interval, Func action) +#pragma warning restore CS1998 // Async method lacks 'await' operators and will run synchronously + { + ArgumentNullException.ThrowIfNull(action); + Console.WriteLine("DebounceAsync " + interval.Milliseconds); + + _timer = GetNewPeriodicTimer(interval.Milliseconds); + + try + { + _ = Task.Run(async () => + { + while (await _timer.WaitForNextTickAsync(_cts.Token)) + { + lock (_syncRoot) + { + if (!_disposed || !_cts.IsCancellationRequested) + { + _cts.CancelAsync(); + Console.WriteLine("Action executing"); + action.Invoke(); + } + } + } + }); + + return true; + } + catch (OperationCanceledException) + { + Console.WriteLine("Canceled"); + return false; // Execution was canceled + } + } + + // Cancel the previous Timer (if existing) + // And create a new Timer with a new CancellationToken + private PeriodicTimer GetNewPeriodicTimer(int delay) + { + _cts.Cancel(); + + if (_timer is not null) + { + _timer.Dispose(); + _timer = null; + } + + _timer = new PeriodicTimer(TimeSpan.FromMilliseconds(delay)); + + _cts.Dispose(); + _cts = new CancellationTokenSource(); + + return _timer; + } + */ + + /// + /// Releases all resources used by the Debounce dispatcher. + /// + public void Dispose() + { + _disposed = true; + _cts?.Cancel(); + } +} diff --git a/tests/Core/Utilities/DebounceTests.cs b/tests/Core/Utilities/DebounceTests.cs new file mode 100644 index 0000000000..41597ca7c5 --- /dev/null +++ b/tests/Core/Utilities/DebounceTests.cs @@ -0,0 +1,134 @@ +// ------------------------------------------------------------------------ +// MIT License - Copyright (c) Microsoft Corporation. All rights reserved. +// ------------------------------------------------------------------------ + +using System; +using System.Collections.Generic; +using System.Diagnostics; +using System.Text; +using System.Threading.Tasks; +using Bunit; +using Microsoft.FluentUI.AspNetCore.Components.Utilities; +using Xunit; +using Xunit.Abstractions; + +namespace Microsoft.FluentUI.AspNetCore.Components.Tests.Utilities; + +public class DebounceTests +{ + [Fact] + public async Task Debounce_Default() + { + // Arrange + var debounce = new Debounce(); + var actionCalled = false; + var watcher = Stopwatch.StartNew(); + + // Act + debounce.Run(50, async () => + { + actionCalled = true; + await Task.CompletedTask; + }); + + // Wait for the debounce to complete + await debounce.CurrentTask; + + // Assert + Assert.True(watcher.ElapsedMilliseconds > 50); + Assert.True(actionCalled); + } + + [Fact] + public async Task Debounce_MultipleCalls() + { + // Arrange + var debounce = new Debounce(); + var actionCalledCount = 0; + var actionCalled = string.Empty; + + // Act + debounce.Run(150, async () => + { + actionCalled = "Step1"; + actionCalledCount++; + await Task.CompletedTask; + }); + + debounce.Run(140, async () => + { + actionCalled = "Step2"; + actionCalledCount++; + await Task.CompletedTask; + }); + + // Wait for the debounce to complete + await debounce.CurrentTask; + + // Assert + Assert.Equal("Step2", actionCalled); + Assert.Equal(1, actionCalledCount); + } + + [Fact] + public async Task Debounce_Disposed() + { + // Arrange + var debounce = new Debounce(); + var actionCalled = false; + + // Act + debounce.Dispose(); + + debounce.Run(50, async () => + { + actionCalled = true; + await Task.CompletedTask; + }); + + // Wait for the debounce to complete + await debounce.CurrentTask; + + // Assert + Assert.False(actionCalled); + } + + [Fact] + public async Task Debounce_Busy() + { + // Arrange + var debounce = new Debounce(); + + // Act + debounce.Run(50, async () => + { + await Task.CompletedTask; + }); + + // Wait for the debounce to complete + await debounce.CurrentTask; + + // Assert + Assert.False(debounce.Busy); + } + + [Fact] + public async Task Debounce_Exception() + { + // Arrange + var debounce = new Debounce(); + + // Act + debounce.Run(50, async () => + { + await Task.CompletedTask; + throw new InvalidProgramException("Error"); // Simulate an exception + }); + + // Wait for the debounce to complete + await debounce.CurrentTask; + + // Assert + Assert.False(debounce.Busy); + } +} From cccfbe2acb229684891e9a947aca6e61a861f92a Mon Sep 17 00:00:00 2001 From: Denis Voituron Date: Fri, 13 Sep 2024 19:05:58 +0200 Subject: [PATCH 2/7] Add Unit Tests --- src/Core/Utilities/Debounce.cs | 65 --------------------------- tests/Core/Utilities/DebounceTests.cs | 40 ++++++++++++++++- 2 files changed, 38 insertions(+), 67 deletions(-) diff --git a/src/Core/Utilities/Debounce.cs b/src/Core/Utilities/Debounce.cs index dc46c3dc81..9f57459802 100644 --- a/src/Core/Utilities/Debounce.cs +++ b/src/Core/Utilities/Debounce.cs @@ -67,71 +67,6 @@ public void Run(int milliseconds, Func action) public Task CurrentTask => _task ?? Task.CompletedTask; - /* - /// - /// Delays the invocation of an action until a predetermined interval has elapsed since the last call. - /// - /// The interval to wait before invoking the action. - /// An action to be invoked after the interval has elapsed. - /// - [System.Diagnostics.CodeAnalysis.SuppressMessage("Usage", "MA0004:Use Task.ConfigureAwait", Justification = "XXX")] -#pragma warning disable CS1998 // Async method lacks 'await' operators and will run synchronously - public async Task DebounceAsync(TimeSpan interval, Func action) -#pragma warning restore CS1998 // Async method lacks 'await' operators and will run synchronously - { - ArgumentNullException.ThrowIfNull(action); - Console.WriteLine("DebounceAsync " + interval.Milliseconds); - - _timer = GetNewPeriodicTimer(interval.Milliseconds); - - try - { - _ = Task.Run(async () => - { - while (await _timer.WaitForNextTickAsync(_cts.Token)) - { - lock (_syncRoot) - { - if (!_disposed || !_cts.IsCancellationRequested) - { - _cts.CancelAsync(); - Console.WriteLine("Action executing"); - action.Invoke(); - } - } - } - }); - - return true; - } - catch (OperationCanceledException) - { - Console.WriteLine("Canceled"); - return false; // Execution was canceled - } - } - - // Cancel the previous Timer (if existing) - // And create a new Timer with a new CancellationToken - private PeriodicTimer GetNewPeriodicTimer(int delay) - { - _cts.Cancel(); - - if (_timer is not null) - { - _timer.Dispose(); - _timer = null; - } - - _timer = new PeriodicTimer(TimeSpan.FromMilliseconds(delay)); - - _cts.Dispose(); - _cts = new CancellationTokenSource(); - - return _timer; - } - */ - /// /// Releases all resources used by the Debounce dispatcher. /// diff --git a/tests/Core/Utilities/DebounceTests.cs b/tests/Core/Utilities/DebounceTests.cs index 41597ca7c5..c466e0e1dc 100644 --- a/tests/Core/Utilities/DebounceTests.cs +++ b/tests/Core/Utilities/DebounceTests.cs @@ -48,14 +48,14 @@ public async Task Debounce_MultipleCalls() var actionCalled = string.Empty; // Act - debounce.Run(150, async () => + debounce.Run(50, async () => { actionCalled = "Step1"; actionCalledCount++; await Task.CompletedTask; }); - debounce.Run(140, async () => + debounce.Run(40, async () => { actionCalled = "Step2"; actionCalledCount++; @@ -70,6 +70,42 @@ public async Task Debounce_MultipleCalls() Assert.Equal(1, actionCalledCount); } + [Fact] + public async Task Debounce_MultipleCalls_Async() + { + // Arrange + var debounce = new Debounce(); + var actionCalledCount = 0; + var actionCalled = string.Empty; + + // Act: simulate two async calls + _ = Task.Run(() => + { + debounce.Run(50, async () => + { + actionCalled = "Step1"; + actionCalledCount++; + await Task.CompletedTask; + }); + }); + + _ = Task.Run(() => + { + debounce.Run(40, async () => + { + actionCalled = "Step2"; + actionCalledCount++; + await Task.CompletedTask; + }); + }); + + await Task.Delay(100); // Wait for the debounce to complete + + // Assert + Assert.Equal("Step2", actionCalled); + Assert.Equal(1, actionCalledCount); + } + [Fact] public async Task Debounce_Disposed() { From a00efd30092e9301ab3991e69dac72cc9cfcb0a8 Mon Sep 17 00:00:00 2001 From: Denis Voituron Date: Fri, 13 Sep 2024 19:24:45 +0200 Subject: [PATCH 3/7] Fix Unit Test --- tests/Core/Utilities/DebounceTests.cs | 2 ++ 1 file changed, 2 insertions(+) diff --git a/tests/Core/Utilities/DebounceTests.cs b/tests/Core/Utilities/DebounceTests.cs index c466e0e1dc..ecf33394f1 100644 --- a/tests/Core/Utilities/DebounceTests.cs +++ b/tests/Core/Utilities/DebounceTests.cs @@ -89,6 +89,8 @@ public async Task Debounce_MultipleCalls_Async() }); }); + await Task.Delay(5); // To ensure the second call is made after the first one + _ = Task.Run(() => { debounce.Run(40, async () => From 41f0e5a596819d6fba45740c15fa5ffa2511b88b Mon Sep 17 00:00:00 2001 From: Denis Voituron Date: Sat, 14 Sep 2024 12:10:33 +0200 Subject: [PATCH 4/7] Add Debounce Timer --- src/Core/Utilities/Debounce2.cs | 38 ++++ .../Utilities/DispatcherTimerExtensions.cs | 72 ++++++++ tests/Core/Utilities/Debounce2Tests.cs | 172 ++++++++++++++++++ tests/Core/Utilities/DebounceTests.cs | 2 +- 4 files changed, 283 insertions(+), 1 deletion(-) create mode 100644 src/Core/Utilities/Debounce2.cs create mode 100644 src/Core/Utilities/DispatcherTimerExtensions.cs create mode 100644 tests/Core/Utilities/Debounce2Tests.cs diff --git a/src/Core/Utilities/Debounce2.cs b/src/Core/Utilities/Debounce2.cs new file mode 100644 index 0000000000..f34a76295b --- /dev/null +++ b/src/Core/Utilities/Debounce2.cs @@ -0,0 +1,38 @@ +// ------------------------------------------------------------------------ +// MIT License - Copyright (c) Microsoft Corporation. All rights reserved. +// ------------------------------------------------------------------------ + +namespace Microsoft.FluentUI.AspNetCore.Components.Utilities; + +/// +/// The Debounce 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. +/// +public class Debounce2 : IDisposable +{ + private bool _disposed; + private readonly System.Timers.Timer _timer = new(); + private TaskCompletionSource? _taskCompletionSource; + + /// + /// Gets a value indicating whether the Debounce dispatcher is busy. + /// + public bool Busy => _taskCompletionSource?.Task.Status == TaskStatus.Running && !_disposed; + + public Task CurrentTask => _taskCompletionSource?.Task ?? Task.CompletedTask; + + public void Run(int milliseconds, Func action) + { + if (!_disposed) + { + _taskCompletionSource = _timer.Debounce(action, milliseconds); + } + } + + public void Dispose() + { + _taskCompletionSource = null; + _timer.Dispose(); + _disposed = true; + } +} diff --git a/src/Core/Utilities/DispatcherTimerExtensions.cs b/src/Core/Utilities/DispatcherTimerExtensions.cs new file mode 100644 index 0000000000..f52adee7a5 --- /dev/null +++ b/src/Core/Utilities/DispatcherTimerExtensions.cs @@ -0,0 +1,72 @@ +// ------------------------------------------------------------------------ +// MIT License - Copyright (c) Microsoft Corporation. All rights reserved. +// ------------------------------------------------------------------------ + +using System.Collections.Concurrent; + +namespace Microsoft.FluentUI.AspNetCore.Components.Utilities; + +/// +/// +/// +internal static class DispatcherTimerExtensions +{ + private static readonly ConcurrentDictionary _debounceInstances = new(); + + public static TaskCompletionSource Debounce(this System.Timers.Timer timer, Func 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 + var item = _debounceInstances.AddOrUpdate( + key: timer, + addValue: new TimerDebounceItem() + { + Status = new TaskCompletionSource(), + Action = action, + }, + updateValueFactory: (k, v) => v.UpdateAction(action)); + + // Start the timer to keep track of the last call here. + timer.Start(); + + return item.Status; + } + + 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(); + } + } + } + + private class TimerDebounceItem + { + public required TaskCompletionSource Status { get; init; } + + public required Func Action { get; set; } + + public TimerDebounceItem UpdateAction(Func action) + { + Action = action; + return this; + } + } +} diff --git a/tests/Core/Utilities/Debounce2Tests.cs b/tests/Core/Utilities/Debounce2Tests.cs new file mode 100644 index 0000000000..0a606e2050 --- /dev/null +++ b/tests/Core/Utilities/Debounce2Tests.cs @@ -0,0 +1,172 @@ +// ------------------------------------------------------------------------ +// MIT License - Copyright (c) Microsoft Corporation. All rights reserved. +// ------------------------------------------------------------------------ + +using System; +using System.Collections.Generic; +using System.Diagnostics; +using System.Text; +using System.Threading.Tasks; +using Bunit; +using Microsoft.FluentUI.AspNetCore.Components.Utilities; +using Xunit; +using Xunit.Abstractions; + +namespace Microsoft.FluentUI.AspNetCore.Components.Tests.Utilities; + +public class Debounce2Tests +{ + [Fact] + public async Task Debounce_Default() + { + // Arrange + var debounce = new Debounce2(); + var actionCalled = false; + var watcher = Stopwatch.StartNew(); + + // Act + debounce.Run(50, async () => + { + actionCalled = true; + await Task.CompletedTask; + }); + + // Wait for the debounce to complete + await debounce.CurrentTask; + + // Assert + Assert.True(watcher.ElapsedMilliseconds >= 50); + Assert.True(actionCalled); + } + + [Fact] + public async Task Debounce_MultipleCalls() + { + // Arrange + var debounce = new Debounce2(); + var actionCalledCount = 0; + var actionCalled = string.Empty; + + // Act + debounce.Run(50, async () => + { + actionCalled = "Step1"; + actionCalledCount++; + await Task.CompletedTask; + }); + + debounce.Run(40, async () => + { + actionCalled = "Step2"; + actionCalledCount++; + await Task.CompletedTask; + }); + + // Wait for the debounce to complete + await debounce.CurrentTask; + + // Assert + Assert.Equal("Step2", actionCalled); + Assert.Equal(1, actionCalledCount); + } + + [Fact] + public async Task Debounce_MultipleCalls_Async() + { + // Arrange + var debounce = new Debounce2(); + var actionCalledCount = 0; + var actionCalled = string.Empty; + + // Act: simulate two async calls + _ = Task.Run(() => + { + debounce.Run(50, async () => + { + actionCalled = "Step1"; + actionCalledCount++; + await Task.CompletedTask; + }); + }); + + await Task.Delay(5); // To ensure the second call is made after the first one + + _ = Task.Run(() => + { + debounce.Run(40, async () => + { + actionCalled = "Step2"; + actionCalledCount++; + await Task.CompletedTask; + }); + }); + + await Task.Delay(100); // Wait for the debounce to complete + + // Assert + Assert.Equal("Step2", actionCalled); + Assert.Equal(1, actionCalledCount); + } + + [Fact] + public async Task Debounce_Disposed() + { + // Arrange + var debounce = new Debounce2(); + var actionCalled = false; + + // Act + debounce.Dispose(); + + debounce.Run(50, async () => + { + actionCalled = true; + await Task.CompletedTask; + }); + + // Wait for the debounce to complete + await debounce.CurrentTask; + + // Assert + Assert.False(actionCalled); + } + + [Fact] + public async Task Debounce_Busy() + { + // Arrange + var debounce = new Debounce2(); + + // Act + debounce.Run(50, async () => + { + await Task.CompletedTask; + }); + + // Wait for the debounce to complete + await debounce.CurrentTask; + + // Assert + Assert.False(debounce.Busy); + } + + [Fact] + public async Task Debounce_Exception() + { + // Arrange + var debounce = new Debounce2(); + + // Act + debounce.Run(50, async () => + { + await Task.CompletedTask; + throw new InvalidProgramException("Error"); // Simulate an exception + }); + + // Wait for the debounce to complete + await debounce.CurrentTask; + + // Assert + Assert.False(debounce.Busy); + } +} diff --git a/tests/Core/Utilities/DebounceTests.cs b/tests/Core/Utilities/DebounceTests.cs index ecf33394f1..dd69df2b8d 100644 --- a/tests/Core/Utilities/DebounceTests.cs +++ b/tests/Core/Utilities/DebounceTests.cs @@ -35,7 +35,7 @@ public async Task Debounce_Default() await debounce.CurrentTask; // Assert - Assert.True(watcher.ElapsedMilliseconds > 50); + Assert.True(watcher.ElapsedMilliseconds >= 50); Assert.True(actionCalled); } From 0248acbc201f6ea45e9fdae19cd596bb7faab866 Mon Sep 17 00:00:00 2001 From: Denis Voituron Date: Sat, 14 Sep 2024 12:23:25 +0200 Subject: [PATCH 5/7] Refactore names --- .../{Debounce2.cs => DebounceAction.cs} | 27 ++++++++++++++-- .../{Debounce.cs => DebounceTask.cs} | 21 +++++++++---- .../Utilities/DispatcherTimerExtensions.cs | 31 ++++++++++++++++++- ...ebounceTests.cs => DebounceActionTests.cs} | 14 ++++----- ...Debounce2Tests.cs => DebounceTaskTests.cs} | 14 ++++----- 5 files changed, 83 insertions(+), 24 deletions(-) rename src/Core/Utilities/{Debounce2.cs => DebounceAction.cs} (52%) rename src/Core/Utilities/{Debounce.cs => DebounceTask.cs} (77%) rename tests/Core/Utilities/{DebounceTests.cs => DebounceActionTests.cs} (92%) rename tests/Core/Utilities/{Debounce2Tests.cs => DebounceTaskTests.cs} (93%) diff --git a/src/Core/Utilities/Debounce2.cs b/src/Core/Utilities/DebounceAction.cs similarity index 52% rename from src/Core/Utilities/Debounce2.cs rename to src/Core/Utilities/DebounceAction.cs index f34a76295b..5f5bf6a017 100644 --- a/src/Core/Utilities/Debounce2.cs +++ b/src/Core/Utilities/DebounceAction.cs @@ -5,30 +5,51 @@ namespace Microsoft.FluentUI.AspNetCore.Components.Utilities; /// -/// The Debounce dispatcher delays the invocation of an action until a predetermined interval has elapsed since the last call. +/// 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. /// -public class Debounce2 : IDisposable +public class DebounceAction : IDisposable { private bool _disposed; private readonly System.Timers.Timer _timer = new(); private TaskCompletionSource? _taskCompletionSource; /// - /// Gets a value indicating whether the Debounce dispatcher is busy. + /// Gets a value indicating whether the DebounceTask dispatcher is busy. /// public bool Busy => _taskCompletionSource?.Task.Status == TaskStatus.Running && !_disposed; + /// + /// Gets the current task. + /// public Task CurrentTask => _taskCompletionSource?.Task ?? Task.CompletedTask; + /// + /// Delays the invocation of an action until a predetermined interval has elapsed since the last call. + /// + /// + /// + /// public void Run(int milliseconds, Func 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); } } + /// + /// Releases all resources used by the DebounceTask dispatcher. + /// public void Dispose() { _taskCompletionSource = null; diff --git a/src/Core/Utilities/Debounce.cs b/src/Core/Utilities/DebounceTask.cs similarity index 77% rename from src/Core/Utilities/Debounce.cs rename to src/Core/Utilities/DebounceTask.cs index 9f57459802..446fd0e698 100644 --- a/src/Core/Utilities/Debounce.cs +++ b/src/Core/Utilities/DebounceTask.cs @@ -5,10 +5,10 @@ namespace Microsoft.FluentUI.AspNetCore.Components.Utilities; /// -/// The Debounce dispatcher delays the invocation of an action until a predetermined interval has elapsed since the last call. +/// 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. /// -internal sealed class Debounce : IDisposable +public sealed class DebounceTask : IDisposable { // https://learn.microsoft.com/en-us/dotnet/standard/threading/timers @@ -23,10 +23,21 @@ internal sealed class Debounce : IDisposable private CancellationTokenSource _cts = new(); /// - /// Gets a value indicating whether the Debounce dispatcher is busy. + /// Gets a value indicating whether the DebounceTask dispatcher is busy. /// public bool Busy => _task?.Status == TaskStatus.Running && !_disposed; + /// + /// Gets the current task. + /// + public Task CurrentTask => _task ?? Task.CompletedTask; + + /// + /// Delays the invocation of an action until a predetermined interval has elapsed since the last call. + /// + /// + /// + /// public void Run(int milliseconds, Func action) { // Check arguments @@ -65,10 +76,8 @@ public void Run(int milliseconds, Func action) } } - public Task CurrentTask => _task ?? Task.CompletedTask; - /// - /// Releases all resources used by the Debounce dispatcher. + /// Releases all resources used by the DebounceTask dispatcher. /// public void Dispose() { diff --git a/src/Core/Utilities/DispatcherTimerExtensions.cs b/src/Core/Utilities/DispatcherTimerExtensions.cs index f52adee7a5..b96c5a9aa8 100644 --- a/src/Core/Utilities/DispatcherTimerExtensions.cs +++ b/src/Core/Utilities/DispatcherTimerExtensions.cs @@ -7,12 +7,22 @@ namespace Microsoft.FluentUI.AspNetCore.Components.Utilities; /// -/// +/// Extension methods for . /// +/// +/// Inspired from Microsoft.Toolkit.Uwp.UI.DispatcherQueueTimerExtensions +/// internal static class DispatcherTimerExtensions { private static readonly ConcurrentDictionary _debounceInstances = new(); + /// + /// Delays the invocation of an action until a predetermined interval has elapsed since the last call. + /// + /// + /// + /// + /// public static TaskCompletionSource Debounce(this System.Timers.Timer timer, Func action, double interval) { // Check and stop any existing timer @@ -41,6 +51,11 @@ public static TaskCompletionSource Debounce(this System.Timers.Timer timer, Func return item.Status; } + /// + /// Timer elapsed event handler. + /// + /// + /// 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 @@ -57,12 +72,26 @@ private static void Timer_Elapsed(object? sender, System.Timers.ElapsedEventArgs } } + /// + /// Timer debounce item. + /// private class TimerDebounceItem { + /// + /// Gets the task completion source. + /// public required TaskCompletionSource Status { get; init; } + /// + /// Gets or sets the action to execute. + /// public required Func Action { get; set; } + /// + /// Updates the action to execute. + /// + /// + /// public TimerDebounceItem UpdateAction(Func action) { Action = action; diff --git a/tests/Core/Utilities/DebounceTests.cs b/tests/Core/Utilities/DebounceActionTests.cs similarity index 92% rename from tests/Core/Utilities/DebounceTests.cs rename to tests/Core/Utilities/DebounceActionTests.cs index dd69df2b8d..29fceb0c77 100644 --- a/tests/Core/Utilities/DebounceTests.cs +++ b/tests/Core/Utilities/DebounceActionTests.cs @@ -14,13 +14,13 @@ namespace Microsoft.FluentUI.AspNetCore.Components.Tests.Utilities; -public class DebounceTests +public class DebounceActionTests { [Fact] public async Task Debounce_Default() { // Arrange - var debounce = new Debounce(); + var debounce = new DebounceAction(); var actionCalled = false; var watcher = Stopwatch.StartNew(); @@ -43,7 +43,7 @@ public async Task Debounce_Default() public async Task Debounce_MultipleCalls() { // Arrange - var debounce = new Debounce(); + var debounce = new DebounceAction(); var actionCalledCount = 0; var actionCalled = string.Empty; @@ -74,7 +74,7 @@ public async Task Debounce_MultipleCalls() public async Task Debounce_MultipleCalls_Async() { // Arrange - var debounce = new Debounce(); + var debounce = new DebounceAction(); var actionCalledCount = 0; var actionCalled = string.Empty; @@ -112,7 +112,7 @@ public async Task Debounce_MultipleCalls_Async() public async Task Debounce_Disposed() { // Arrange - var debounce = new Debounce(); + var debounce = new DebounceAction(); var actionCalled = false; // Act @@ -135,7 +135,7 @@ public async Task Debounce_Disposed() public async Task Debounce_Busy() { // Arrange - var debounce = new Debounce(); + var debounce = new DebounceAction(); // Act debounce.Run(50, async () => @@ -154,7 +154,7 @@ public async Task Debounce_Busy() public async Task Debounce_Exception() { // Arrange - var debounce = new Debounce(); + var debounce = new DebounceAction(); // Act debounce.Run(50, async () => diff --git a/tests/Core/Utilities/Debounce2Tests.cs b/tests/Core/Utilities/DebounceTaskTests.cs similarity index 93% rename from tests/Core/Utilities/Debounce2Tests.cs rename to tests/Core/Utilities/DebounceTaskTests.cs index 0a606e2050..15a23250ee 100644 --- a/tests/Core/Utilities/Debounce2Tests.cs +++ b/tests/Core/Utilities/DebounceTaskTests.cs @@ -14,13 +14,13 @@ namespace Microsoft.FluentUI.AspNetCore.Components.Tests.Utilities; -public class Debounce2Tests +public class DebounceTaskTests { [Fact] public async Task Debounce_Default() { // Arrange - var debounce = new Debounce2(); + var debounce = new DebounceTask(); var actionCalled = false; var watcher = Stopwatch.StartNew(); @@ -43,7 +43,7 @@ public async Task Debounce_Default() public async Task Debounce_MultipleCalls() { // Arrange - var debounce = new Debounce2(); + var debounce = new DebounceTask(); var actionCalledCount = 0; var actionCalled = string.Empty; @@ -74,7 +74,7 @@ public async Task Debounce_MultipleCalls() public async Task Debounce_MultipleCalls_Async() { // Arrange - var debounce = new Debounce2(); + var debounce = new DebounceTask(); var actionCalledCount = 0; var actionCalled = string.Empty; @@ -112,7 +112,7 @@ public async Task Debounce_MultipleCalls_Async() public async Task Debounce_Disposed() { // Arrange - var debounce = new Debounce2(); + var debounce = new DebounceTask(); var actionCalled = false; // Act @@ -135,7 +135,7 @@ public async Task Debounce_Disposed() public async Task Debounce_Busy() { // Arrange - var debounce = new Debounce2(); + var debounce = new DebounceTask(); // Act debounce.Run(50, async () => @@ -154,7 +154,7 @@ public async Task Debounce_Busy() public async Task Debounce_Exception() { // Arrange - var debounce = new Debounce2(); + var debounce = new DebounceTask(); // Act debounce.Run(50, async () => From 86d8ea446b8531b1a28eda5874c3657dee5773a7 Mon Sep 17 00:00:00 2001 From: Denis Voituron Date: Sat, 14 Sep 2024 12:32:00 +0200 Subject: [PATCH 6/7] Fix Task MultipleCalls --- src/Core/Utilities/DebounceTask.cs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/Core/Utilities/DebounceTask.cs b/src/Core/Utilities/DebounceTask.cs index 446fd0e698..7087a66d5b 100644 --- a/src/Core/Utilities/DebounceTask.cs +++ b/src/Core/Utilities/DebounceTask.cs @@ -60,9 +60,9 @@ public void Run(int milliseconds, Func action) _task = Task.Delay(TimeSpan.FromMilliseconds(milliseconds), _cts.Token) .ContinueWith(t => { - lock (_syncRoot) + if (!_disposed && !_cts.IsCancellationRequested) { - if (!_disposed && !_cts.IsCancellationRequested) + lock (_syncRoot) { _ = action.Invoke(); } From 360e8dd2e8237022bcbba19bb609a2913d14f539 Mon Sep 17 00:00:00 2001 From: Denis Voituron Date: Mon, 16 Sep 2024 12:01:13 +0200 Subject: [PATCH 7/7] Refactoring to create a common class Debounce --- src/Core/Utilities/Debounce.cs | 13 ++++ .../{ => InternalDebounce}/DebounceAction.cs | 6 +- .../{ => InternalDebounce}/DebounceTask.cs | 9 +-- .../DispatcherTimerExtensions.cs | 5 +- tests/Core/Utilities/DebounceActionTests.cs | 64 +++++++++++++++++++ tests/Core/Utilities/DebounceTaskTests.cs | 60 +++++++++++++++++ 6 files changed, 147 insertions(+), 10 deletions(-) create mode 100644 src/Core/Utilities/Debounce.cs rename src/Core/Utilities/{ => InternalDebounce}/DebounceAction.cs (90%) rename src/Core/Utilities/{ => InternalDebounce}/DebounceTask.cs (92%) rename src/Core/Utilities/{ => InternalDebounce}/DispatcherTimerExtensions.cs (92%) diff --git a/src/Core/Utilities/Debounce.cs b/src/Core/Utilities/Debounce.cs new file mode 100644 index 0000000000..6cac0f44b1 --- /dev/null +++ b/src/Core/Utilities/Debounce.cs @@ -0,0 +1,13 @@ +// ------------------------------------------------------------------------ +// MIT License - Copyright (c) Microsoft Corporation. All rights reserved. +// ------------------------------------------------------------------------ + +namespace Microsoft.FluentUI.AspNetCore.Components.Utilities; + +/// +/// 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. +/// +public sealed class Debounce : InternalDebounce.DebounceTask +{ +} diff --git a/src/Core/Utilities/DebounceAction.cs b/src/Core/Utilities/InternalDebounce/DebounceAction.cs similarity index 90% rename from src/Core/Utilities/DebounceAction.cs rename to src/Core/Utilities/InternalDebounce/DebounceAction.cs index 5f5bf6a017..907da424a2 100644 --- a/src/Core/Utilities/DebounceAction.cs +++ b/src/Core/Utilities/InternalDebounce/DebounceAction.cs @@ -2,13 +2,14 @@ // MIT License - Copyright (c) Microsoft Corporation. All rights reserved. // ------------------------------------------------------------------------ -namespace Microsoft.FluentUI.AspNetCore.Components.Utilities; +namespace Microsoft.FluentUI.AspNetCore.Components.Utilities.InternalDebounce; /// /// 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. /// -public class DebounceAction : IDisposable +[Obsolete("Use Debounce, which inherits from DebounceTask.")] +internal class DebounceAction : IDisposable { private bool _disposed; private readonly System.Timers.Timer _timer = new(); @@ -55,5 +56,6 @@ public void Dispose() _taskCompletionSource = null; _timer.Dispose(); _disposed = true; + GC.SuppressFinalize(this); } } diff --git a/src/Core/Utilities/DebounceTask.cs b/src/Core/Utilities/InternalDebounce/DebounceTask.cs similarity index 92% rename from src/Core/Utilities/DebounceTask.cs rename to src/Core/Utilities/InternalDebounce/DebounceTask.cs index 7087a66d5b..79746d957c 100644 --- a/src/Core/Utilities/DebounceTask.cs +++ b/src/Core/Utilities/InternalDebounce/DebounceTask.cs @@ -2,16 +2,14 @@ // MIT License - Copyright (c) Microsoft Corporation. All rights reserved. // ------------------------------------------------------------------------ -namespace Microsoft.FluentUI.AspNetCore.Components.Utilities; +namespace Microsoft.FluentUI.AspNetCore.Components.Utilities.InternalDebounce; /// /// 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. /// -public sealed class DebounceTask : IDisposable +public class DebounceTask : IDisposable { - // https://learn.microsoft.com/en-us/dotnet/standard/threading/timers - #if NET9_0_OR_GREATER private readonly System.Threading.Lock _syncRoot = new(); #else @@ -20,7 +18,7 @@ public sealed class DebounceTask : IDisposable private bool _disposed; private Task? _task; - private CancellationTokenSource _cts = new(); + private CancellationTokenSource? _cts; /// /// Gets a value indicating whether the DebounceTask dispatcher is busy. @@ -68,7 +66,6 @@ public void Run(int milliseconds, Func action) } } }, _cts.Token, TaskContinuationOptions.OnlyOnRanToCompletion, TaskScheduler.Current); - } catch (TaskCanceledException) { diff --git a/src/Core/Utilities/DispatcherTimerExtensions.cs b/src/Core/Utilities/InternalDebounce/DispatcherTimerExtensions.cs similarity index 92% rename from src/Core/Utilities/DispatcherTimerExtensions.cs rename to src/Core/Utilities/InternalDebounce/DispatcherTimerExtensions.cs index b96c5a9aa8..1fd89d3861 100644 --- a/src/Core/Utilities/DispatcherTimerExtensions.cs +++ b/src/Core/Utilities/InternalDebounce/DispatcherTimerExtensions.cs @@ -4,7 +4,7 @@ using System.Collections.Concurrent; -namespace Microsoft.FluentUI.AspNetCore.Components.Utilities; +namespace Microsoft.FluentUI.AspNetCore.Components.Utilities.InternalDebounce; /// /// Extension methods for . @@ -36,6 +36,7 @@ public static TaskCompletionSource Debounce(this System.Timers.Timer timer, Func 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() @@ -43,7 +44,7 @@ public static TaskCompletionSource Debounce(this System.Timers.Timer timer, Func Status = new TaskCompletionSource(), Action = action, }, - updateValueFactory: (k, v) => v.UpdateAction(action)); + updateValueFactory: updateValueFactory); // Start the timer to keep track of the last call here. timer.Start(); diff --git a/tests/Core/Utilities/DebounceActionTests.cs b/tests/Core/Utilities/DebounceActionTests.cs index 29fceb0c77..f103ed9101 100644 --- a/tests/Core/Utilities/DebounceActionTests.cs +++ b/tests/Core/Utilities/DebounceActionTests.cs @@ -9,13 +9,24 @@ using System.Threading.Tasks; using Bunit; using Microsoft.FluentUI.AspNetCore.Components.Utilities; +using Microsoft.FluentUI.AspNetCore.Components.Utilities.InternalDebounce; +using Microsoft.VisualStudio.TestPlatform.Utilities; using Xunit; using Xunit.Abstractions; namespace Microsoft.FluentUI.AspNetCore.Components.Tests.Utilities; +#pragma warning disable CS0618 // Type or member is obsolete + public class DebounceActionTests { + private readonly ITestOutputHelper Output; + + public DebounceActionTests(ITestOutputHelper output) + { + Output = output; + } + [Fact] public async Task Debounce_Default() { @@ -169,4 +180,57 @@ public async Task Debounce_Exception() // Assert Assert.False(debounce.Busy); } + + [Fact] + public void Debounce_DelayMustBePositive() + { + // Arrange + var debounce = new DebounceAction(); + + // Act + Assert.Throws(() => + { + debounce.Run(-10, () => Task.CompletedTask); + }); + } + + [Fact] + public async Task Debounce_FirstRunAlreadyStarted() + { + // Arrange + var debounce = new DebounceAction(); + var actionCalledCount = 0; + + // Act + debounce.Run(10, async () => + { + Output.WriteLine("Step1 - Started"); + + await Task.Delay(100); + actionCalledCount++; + + Output.WriteLine("Step1 - Completed"); + }); + + await Task.Delay(20); // Wait for Step1 to start. + + debounce.Run(10, async () => + { + Output.WriteLine("Step2 - Started"); + + await Task.CompletedTask; + actionCalledCount++; + + Output.WriteLine("Step2 - Completed"); + }); + + // Wait for the debounce to complete + await debounce.CurrentTask; + await Task.Delay(200); + + // Assert + Assert.Equal(2, actionCalledCount); + } } + +#pragma warning restore CS0618 // Type or member is obsolete diff --git a/tests/Core/Utilities/DebounceTaskTests.cs b/tests/Core/Utilities/DebounceTaskTests.cs index 15a23250ee..1ab311f827 100644 --- a/tests/Core/Utilities/DebounceTaskTests.cs +++ b/tests/Core/Utilities/DebounceTaskTests.cs @@ -9,6 +9,8 @@ using System.Threading.Tasks; using Bunit; using Microsoft.FluentUI.AspNetCore.Components.Utilities; +using Microsoft.FluentUI.AspNetCore.Components.Utilities.InternalDebounce; +using Microsoft.VisualStudio.TestPlatform.Utilities; using Xunit; using Xunit.Abstractions; @@ -16,6 +18,13 @@ namespace Microsoft.FluentUI.AspNetCore.Components.Tests.Utilities; public class DebounceTaskTests { + private readonly ITestOutputHelper Output; + + public DebounceTaskTests(ITestOutputHelper output) + { + Output = output; + } + [Fact] public async Task Debounce_Default() { @@ -169,4 +178,55 @@ public async Task Debounce_Exception() // Assert Assert.False(debounce.Busy); } + + [Fact] + public void Debounce_DelayMustBePositive() + { + // Arrange + var debounce = new DebounceTask(); + + // Act + Assert.Throws(() => + { + debounce.Run(-10, () => Task.CompletedTask); + }); + } + + [Fact] + public async Task Debounce_FirstRunAlreadyStarted() + { + // Arrange + var debounce = new DebounceTask(); + var actionCalledCount = 0; + + // Act + debounce.Run(10, async () => + { + Output.WriteLine("Step1 - Started"); + + await Task.Delay(100); + actionCalledCount++; + + Output.WriteLine("Step1 - Completed"); + }); + + await Task.Delay(20); // Wait for Step1 to start. + + debounce.Run(10, async () => + { + Output.WriteLine("Step2 - Started"); + + await Task.CompletedTask; + actionCalledCount++; + + Output.WriteLine("Step2 - Completed"); + }); + + // Wait for the debounce to complete + await debounce.CurrentTask; + await Task.Delay(200); + + // Assert + Assert.Equal(2, actionCalledCount); + } }