rework throttle

reuse throttle mechanism for catching global keys
This commit is contained in:
Oleksandr Bezdieniezhnykh
2024-08-14 02:02:26 +03:00
parent 468d28d9d8
commit 78776d37bd
6 changed files with 38 additions and 28 deletions
@@ -1,16 +0,0 @@
namespace Azaion.Annotator.Extensions;
public static class FuncExtensions
{
private static CancellationTokenSource? _lastCToken;
public static Action Debounce(this Action func, TimeSpan? throttleTime = null) =>
() =>
{
_lastCToken?.Cancel();
var tokenSrc = _lastCToken = new CancellationTokenSource();
Task.Delay(throttleTime ?? TimeSpan.FromMilliseconds(500), tokenSrc.Token)
.ContinueWith(_ => func(), tokenSrc.Token);
};
}
@@ -0,0 +1,16 @@
namespace Azaion.Annotator.Extensions;
public static class ThrottleExt
{
private static bool _throttleOn;
public static async Task Throttle(Func<Task> func, TimeSpan? throttleTime = null)
{
if (_throttleOn)
return;
_throttleOn = true;
await func();
await Task.Delay(throttleTime ?? TimeSpan.FromMilliseconds(500));
_throttleOn = false;
}
}