2022-04-10 03:38:39 +03:00
|
|
|
|
using System;
|
|
|
|
|
using System.Threading;
|
|
|
|
|
using System.Threading.Tasks;
|
|
|
|
|
|
|
|
|
|
namespace YoutubeDownloader.Core.Utils;
|
|
|
|
|
|
2023-12-10 23:57:23 +02:00
|
|
|
|
public class ThrottleLock(TimeSpan interval) : IDisposable
|
2022-04-10 03:38:39 +03:00
|
|
|
|
{
|
|
|
|
|
private readonly SemaphoreSlim _semaphore = new(1, 1);
|
|
|
|
|
private DateTimeOffset _lastRequestInstant = DateTimeOffset.MinValue;
|
|
|
|
|
|
|
|
|
|
public async Task WaitAsync(CancellationToken cancellationToken = default)
|
|
|
|
|
{
|
|
|
|
|
await _semaphore.WaitAsync(cancellationToken);
|
|
|
|
|
|
|
|
|
|
try
|
|
|
|
|
{
|
|
|
|
|
var timePassedSinceLastRequest = DateTimeOffset.Now - _lastRequestInstant;
|
|
|
|
|
|
2023-12-10 23:57:23 +02:00
|
|
|
|
var remainingTime = interval - timePassedSinceLastRequest;
|
2022-04-10 03:38:39 +03:00
|
|
|
|
if (remainingTime > TimeSpan.Zero)
|
|
|
|
|
await Task.Delay(remainingTime, cancellationToken);
|
|
|
|
|
|
|
|
|
|
_lastRequestInstant = DateTimeOffset.Now;
|
|
|
|
|
}
|
|
|
|
|
finally
|
|
|
|
|
{
|
|
|
|
|
_semaphore.Release();
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
public void Dispose() => _semaphore.Dispose();
|
2023-10-21 17:58:59 +03:00
|
|
|
|
}
|