diff options
Diffstat (limited to 'src')
| -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 |
