mirror of
https://github.com/azaion/annotations.git
synced 2026-04-22 12:46:30 +00:00
failsafe load dlls
add user config queue offsets throttle improvements
This commit is contained in:
@@ -1,57 +1,22 @@
|
||||
using System.Collections.Concurrent;
|
||||
|
||||
namespace Azaion.Common.Extensions;
|
||||
namespace Azaion.Common.Extensions;
|
||||
|
||||
public static class ThrottleExt
|
||||
{
|
||||
private static ConcurrentDictionary<Guid, bool> _taskStates = new();
|
||||
private static readonly Dictionary<Delegate, DateTime> LastExecution = new();
|
||||
private static readonly object Lock = new();
|
||||
|
||||
public static async Task ThrottleRunFirst(Func<Task> func, Guid actionId, TimeSpan? throttleTime = null, CancellationToken cancellationToken = default)
|
||||
public static async Task Throttle(this Func<Task> func, TimeSpan interval, CancellationToken ct = default)
|
||||
{
|
||||
if (_taskStates.ContainsKey(actionId) && _taskStates[actionId])
|
||||
return;
|
||||
ArgumentNullException.ThrowIfNull(func);
|
||||
|
||||
_taskStates[actionId] = true;
|
||||
try
|
||||
lock (Lock)
|
||||
{
|
||||
await func();
|
||||
if (LastExecution.ContainsKey(func) && DateTime.UtcNow - LastExecution[func] < interval)
|
||||
return;
|
||||
|
||||
func();
|
||||
LastExecution[func] = DateTime.UtcNow;
|
||||
}
|
||||
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;
|
||||
}
|
||||
|
||||
}
|
||||
Reference in New Issue
Block a user