mirror of
https://github.com/azaion/annotations.git
synced 2026-04-22 16:16:31 +00:00
fix initialization, throttle operations
day/winter/night switcher fixes
This commit is contained in:
@@ -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;
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user