Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Next Next commit
Fix the Debounce component
  • Loading branch information
dvoituron committed Oct 4, 2024
commit 91d131fb5caf02bb7c24c16a44526aea664cf748
38 changes: 27 additions & 11 deletions src/Core/Utilities/InternalDebounce/DispatcherTimerExtensions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -35,22 +35,19 @@ public static TaskCompletionSource Debounce(this System.Timers.Timer timer, Func
// 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.Status.SetCanceled();
v.Status = new TaskCompletionSource();
return v.UpdateAction(action);
}

var item = _debounceInstances.AddOrUpdate(
key: timer,
addValue: new TimerDebounceItem()
{
Status = new TaskCompletionSource(),
Action = action,
},
updateValueFactory: updateValueFactory);
updateValueFactory: (k, v) =>
{
v.Status.SetCanceled();
v.Status = new TaskCompletionSource();
return v.UpdateAction(action);
});

// Start the timer to keep track of the last call here.
timer.Start();
Expand All @@ -73,8 +70,27 @@ private static void Timer_Elapsed(object? sender, System.Timers.ElapsedEventArgs

if (_debounceInstances.TryRemove(timer, out var item))
{
_ = (item?.Action.Invoke());
item?.Status.SetResult();
if (item == null)
{
return;
}

var task = item.Action.Invoke();
task.ContinueWith(t =>
{
if (t.IsFaulted)
{
item.Status.SetException(t.Exception);
}
else if (t.IsCanceled)
{
item.Status.SetCanceled();
}
else
{
item.Status.SetResult();
}
});
}
}
}
Expand Down
32 changes: 26 additions & 6 deletions tests/Core/Utilities/DebounceActionTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -199,15 +199,35 @@ public async Task Debounce_Busy()
[Fact]
public async Task Debounce_Exception()
{
// Act
Debounce.Run(50, async () =>
await Assert.ThrowsAsync<AggregateException>(async () =>
{
await Task.CompletedTask;
throw new InvalidProgramException("Error"); // Simulate an exception
// Act
Debounce.Run(50, async () =>
{
await Task.CompletedTask;
throw new InvalidProgramException("Error"); // Simulate an exception
});

// Wait for the debounce to complete
await Debounce.CurrentTask;
});

// Wait for the debounce to complete
await Debounce.CurrentTask;
// Assert
Assert.False(Debounce.Busy);
}

[Fact]
public async Task Debounce_AsyncException()
{
await Assert.ThrowsAsync<AggregateException>(async () =>
{
// Act
await Debounce.RunAsync(50, async () =>
{
await Task.CompletedTask;
throw new InvalidProgramException("Error"); // Simulate an exception
});
});

// Assert
Assert.False(Debounce.Busy);
Expand Down