Files
annotations/Azaion.Common/Extensions/ThrottleExtensions.cs
T
2025-02-26 22:09:07 +02:00

57 lines
1.6 KiB
C#

using System.Collections.Concurrent;
namespace Azaion.Common.Extensions;
public static class ThrottleExt
{
private static ConcurrentDictionary<Guid, bool> _taskStates = new();
public static async Task ThrottleRunFirst(Func<Task> func, Guid actionId, TimeSpan? throttleTime = null, CancellationToken cancellationToken = default)
{
if (_taskStates.ContainsKey(actionId) && _taskStates[actionId])
return;
_taskStates[actionId] = true;
try
{
await func();
}
catch (Exception e)
{
Console.WriteLine(e);
}
_ = Task.Run(async () =>
{
await Task.Delay(throttleTime ?? TimeSpan.FromMilliseconds(500), cancellationToken);
_taskStates[actionId] = false;
}, cancellationToken);
}
public static async Task ThrottleRunAfter(Func<Task> func, Guid actionId, TimeSpan? throttleTime = null, CancellationToken cancellationToken = default)
{
if (_taskStates.ContainsKey(actionId) && _taskStates[actionId])
return;
_taskStates[actionId] = true;
_ = Task.Run(async () =>
{
try
{
await Task.Delay(throttleTime ?? TimeSpan.FromMilliseconds(500), cancellationToken);
await func();
}
catch (Exception)
{
_taskStates[actionId] = false;
}
finally
{
_taskStates[actionId] = false;
}
}, cancellationToken);
await Task.CompletedTask;
}
}