Remotely/Shared/Utilities/Debouncer.cs

30 lines
890 B
C#
Raw Blame History

This file contains invisible Unicode characters

This file contains invisible Unicode characters that are indistinguishable to humans but may be processed differently by a computer. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Text;
using System.Threading.Tasks;
using System.Timers;
namespace Remotely.Shared.Utilities
{
public static class Debouncer
{
private static readonly ConcurrentDictionary<object, Timer> _timers = new();
public static void Debounce(TimeSpan wait, Action action, [CallerMemberName] string key = "")
{
if (_timers.TryRemove(key, out var timer))
{
timer.Stop();
timer.Dispose();
}
timer = new Timer(wait.TotalMilliseconds)
{
AutoReset = false
};
timer.Elapsed += (s, e) => action();
_timers.TryAdd(key, timer);
timer.Start();
}
}
}