28 lines
863 B
C#
28 lines
863 B
C#
using Livia.Utility.DependencyInjection;
|
|
using Microsoft.Extensions.DependencyInjection;
|
|
using Microsoft.Extensions.Logging;
|
|
|
|
namespace Livia.Utility;
|
|
|
|
public class DebounceHelper(TimeSpan timespan)
|
|
{
|
|
private DateTime _lastFireTime = DateTime.UnixEpoch;
|
|
private readonly object _mutex = new();
|
|
private readonly ILogger _logger = ActivatorUtilities.GetServiceOrCreateInstance<ILogger>(ServiceProviderFactory.ServiceProvider);
|
|
|
|
public bool TryFire()
|
|
{
|
|
lock (_mutex)
|
|
{
|
|
DateTime now = DateTime.Now;
|
|
TimeSpan diff = now - _lastFireTime;
|
|
if (diff <= timespan)
|
|
{
|
|
_logger.LogInformation("Event fired too soon, {diff} < {timespan}", diff, timespan);
|
|
return false;
|
|
}
|
|
_lastFireTime = now;
|
|
return true;
|
|
}
|
|
}
|
|
} |