diff options
| author | JP Dillingham <jp@dillingham.me> | 2025-10-12 13:18:07 -0500 |
|---|---|---|
| committer | JP Dillingham <jp@dillingham.me> | 2025-10-12 13:18:07 -0500 |
| commit | 339641fb463420fa331fad3793885d7af83d27a9 (patch) | |
| tree | dd7529d72755c886a39dee277f5667c274b8d41a | |
| parent | 78a9e94a4bfd5e67e0751fe573ef948790020eae (diff) | |
| download | slskd-339641fb463420fa331fad3793885d7af83d27a9.tar.gz | |
add a concurrency limit to RateLimiter
| -rw-r--r-- | src/slskd/Common/RateLimiter.cs | 26 |
1 files changed, 23 insertions, 3 deletions
diff --git a/src/slskd/Common/RateLimiter.cs b/src/slskd/Common/RateLimiter.cs index 8a7a63c6..b57c2f88 100644 --- a/src/slskd/Common/RateLimiter.cs +++ b/src/slskd/Common/RateLimiter.cs @@ -19,6 +19,7 @@ namespace slskd { using System; using System.ComponentModel; + using System.Threading; /// <summary> /// Ensures a minimum interval between successive invocations of a delegate. @@ -29,8 +30,11 @@ namespace slskd /// Initializes a new instance of the <see cref="RateLimiter"/> class. /// </summary> /// <param name="interval">The minimum interval between invocations.</param> + /// <param name="concurrencyLimit"> + /// Limit the number of concurrent executions of the specified action, in cases where the logic runs slower than the configured interval. Set this to null to remove the limit. + /// </param> /// <param name="flushOnDispose">A value indicating whether pending action(s) should be executed during disposal.</param> - public RateLimiter(int interval, bool flushOnDispose = false) + public RateLimiter(int interval, int? concurrencyLimit = 1, bool flushOnDispose = false) { Timer = new System.Timers.Timer(interval) { @@ -40,6 +44,11 @@ namespace slskd Timer.Elapsed += Timer_Elapsed; FlushOnDispose = flushOnDispose; + + if (concurrencyLimit.HasValue) + { + ConcurrentExecutionPreventionSemaphore = new SemaphoreSlim(concurrencyLimit.Value, concurrencyLimit.Value); + } } private bool Disposed { get; set; } @@ -47,6 +56,7 @@ namespace slskd private bool Init { get; set; } private Action Staged { get; set; } private System.Timers.Timer Timer { get; set; } + private SemaphoreSlim ConcurrentExecutionPreventionSemaphore { get; } = null; /// <summary> /// Releases all resources used by the <see cref="Component"/>. @@ -102,8 +112,18 @@ namespace slskd private void Timer_Elapsed(object sender, EventArgs args) { - Staged?.Invoke(); - Staged = null; + if (ConcurrentExecutionPreventionSemaphore?.Wait(0) ?? true) + { + try + { + Staged?.Invoke(); + Staged = null; + } + finally + { + ConcurrentExecutionPreventionSemaphore?.Release(); + } + } } } }
\ No newline at end of file |
