fix initialization, throttle operations

day/winter/night switcher fixes
This commit is contained in:
Alex Bezdieniezhnykh
2025-02-19 23:07:16 +02:00
parent c314268d1e
commit d1af7958f8
17 changed files with 170 additions and 88 deletions
+35 -14
View File
@@ -1,34 +1,55 @@
namespace Azaion.Common.Extensions;
using System.Collections.Concurrent;
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)
private static ConcurrentDictionary<Guid, bool> _taskStates = new();
public static async Task ThrottleRunFirst(Func<Task> func, Guid actionId, TimeSpan? throttleTime = null, CancellationToken cancellationToken = default)
{
if (_throttleRunFirstOn)
if (_taskStates.ContainsKey(actionId) && _taskStates[actionId])
return;
_throttleRunFirstOn = true;
await func();
_taskStates[actionId] = true;
try
{
await func();
}
catch (Exception e)
{
Console.WriteLine(e);
}
_ = Task.Run(async () =>
{
await Task.Delay(throttleTime ?? TimeSpan.FromMilliseconds(500), cancellationToken);
_throttleRunFirstOn = false;
_taskStates[actionId] = false;
}, cancellationToken);
}
private static bool _throttleRunAfter;
public static async Task ThrottleRunAfter(this Func<Task> func, TimeSpan? throttleTime = null, CancellationToken cancellationToken = default)
public static async Task ThrottleRunAfter(Func<Task> func, Guid actionId, TimeSpan? throttleTime = null, CancellationToken cancellationToken = default)
{
if (_throttleRunAfter)
if (_taskStates.ContainsKey(actionId) && _taskStates[actionId])
return;
_throttleRunAfter = true;
_taskStates[actionId] = true;
_ = Task.Run(async () =>
{
await Task.Delay(throttleTime ?? TimeSpan.FromMilliseconds(500), cancellationToken);
await func();
_throttleRunAfter = false;
try
{
await Task.Delay(throttleTime ?? TimeSpan.FromMilliseconds(500), cancellationToken);
await func();
}
catch (Exception ex)
{
_taskStates[actionId] = false;
}
finally
{
_taskStates[actionId] = false;
}
}, cancellationToken);
await Task.CompletedTask;
}