From 39bb1b9cc7f1e9afcefa535f4dcc2344fa023da1 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sun, 3 Aug 2025 15:44:41 -0500 Subject: add CurrentRequestReceiveRate metric and TimedCounter to implement it --- src/slskd/Common/TimedCounter.cs | 89 ++++++++++++++++++++++++++++++++++++++++ 1 file changed, 89 insertions(+) create mode 100644 src/slskd/Common/TimedCounter.cs (limited to 'src/slskd/Common/TimedCounter.cs') diff --git a/src/slskd/Common/TimedCounter.cs b/src/slskd/Common/TimedCounter.cs new file mode 100644 index 00000000..c65ca7e3 --- /dev/null +++ b/src/slskd/Common/TimedCounter.cs @@ -0,0 +1,89 @@ +// +// Copyright (c) slskd Team. All rights reserved. +// +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU Affero General Public License as published +// by the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU Affero General Public License for more details. +// +// You should have received a copy of the GNU Affero General Public License +// along with this program. If not, see https://www.gnu.org/licenses/. +// + +using System; +using System.Timers; + +namespace slskd +{ + /// + /// A counter that counts up over a set time period. + /// + public class TimedCounter : IDisposable + { + /// + /// Initializes a new instance of the class. + /// + /// The interval at which the OnElapsed delegate is called and the count resets. + /// The delagate to invoke with the current count when the timer elapses. + public TimedCounter(TimeSpan interval, Action onElapsed) + { + OnElapsed = onElapsed; + + Timer = new Timer(interval); + Timer.Elapsed += Elapsed; + Timer.Start(); + } + + /// + /// Gets the current count. + /// + public long Count { get; private set; } = 0; + + private Timer Timer { get; } + private Action OnElapsed { get; } + private bool Disposed { get; set; } + + /// + /// Counts up by the specified . + /// + /// The number to add to the count. + public void CountUp(long count = 1) + { + Count += count; + } + + /// + /// Disposes this instance. + /// + public void Dispose() + { + Dispose(true); + GC.SuppressFinalize(this); + } + + protected virtual void Dispose(bool disposing) + { + if (!Disposed) + { + if (disposing) + { + Timer.Dispose(); + } + + Disposed = true; + } + } + + private void Elapsed(object sender, ElapsedEventArgs args) + { + var count = Count; + Count = 0; + OnElapsed?.Invoke(count); + } + } +} -- cgit v1.2.3