From 339641fb463420fa331fad3793885d7af83d27a9 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sun, 12 Oct 2025 13:18:07 -0500 Subject: add a concurrency limit to RateLimiter --- src/slskd/Common/RateLimiter.cs | 26 +++++++++++++++++++++++--- 1 file changed, 23 insertions(+), 3 deletions(-) (limited to 'src') 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; /// /// Ensures a minimum interval between successive invocations of a delegate. @@ -29,8 +30,11 @@ namespace slskd /// Initializes a new instance of the class. /// /// The minimum interval between invocations. + /// + /// 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. + /// /// A value indicating whether pending action(s) should be executed during disposal. - 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; /// /// Releases all resources used by the . @@ -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 -- cgit v1.2.3