Files
annotations/Azaion.Common/Extensions/ThrottleExtensions.cs
T
Alex Bezdieniezhnykh 961d2499de fix inference
fix small issues
2025-02-14 09:00:04 +02:00

36 lines
1.1 KiB
C#

namespace Azaion.Common.Extensions;
public static class ThrottleExt
{
private static bool _throttleRunFirstOn;
public static async Task ThrottleRunFirst(this Func<Task> func, TimeSpan? throttleTime = null, CancellationToken cancellationToken = default)
{
if (_throttleRunFirstOn)
return;
_throttleRunFirstOn = true;
await func();
_ = Task.Run(async () =>
{
await Task.Delay(throttleTime ?? TimeSpan.FromMilliseconds(500), cancellationToken);
_throttleRunFirstOn = false;
}, cancellationToken);
}
private static bool _throttleRunAfter;
public static async Task ThrottleRunAfter(this Func<Task> func, TimeSpan? throttleTime = null, CancellationToken cancellationToken = default)
{
if (_throttleRunAfter)
return;
_throttleRunAfter = true;
_ = Task.Run(async () =>
{
await Task.Delay(throttleTime ?? TimeSpan.FromMilliseconds(500), cancellationToken);
await func();
_throttleRunAfter = false;
}, cancellationToken);
await Task.CompletedTask;
}
}