From e99e2d817ada2c9e8af430cfd928a8870fce66e2 Mon Sep 17 00:00:00 2001 From: John Colvin Date: Wed, 4 Sep 2024 09:49:28 -0400 Subject: [PATCH] fix: Remove redundant SparkTimer threads This addresses some slowness on the front end. Prior to this commit, each ThreadedBlackboard would start its own timer thread. Since multiple ThreadedBlackboard run concurrently, this multiplied the frequency of the SparkTimer callbacks by the number of active ThreadedBlackboards. The fix is to start this thread in an IShellDaemon rather than the ThreadedBlackboard. This avoids duplicate threads because the former is guarenteed to be instantiated only once, via dependency injection. --- .../spark/AW2/Misc/ThreadedBlackboard.cs | 9 ----- .../spark/Daemons/ThreadedBlackboardDaemon.cs | 40 +++++++++++++++++++ 2 files changed, 40 insertions(+), 9 deletions(-) create mode 100644 src/client/spark/Daemons/ThreadedBlackboardDaemon.cs diff --git a/src/client/spark/AW2/Misc/ThreadedBlackboard.cs b/src/client/spark/AW2/Misc/ThreadedBlackboard.cs index d00a616ae..328afb3ad 100644 --- a/src/client/spark/AW2/Misc/ThreadedBlackboard.cs +++ b/src/client/spark/AW2/Misc/ThreadedBlackboard.cs @@ -37,15 +37,6 @@ namespace mbts.spark { _bus = bus; _bb_name = name; subscribe(SparkTags.SparkTimer); - System.Threading.Thread timer_thread = new System.Threading.Thread(() => { - DateTime start_time = DateTime.Now; - while (true) { - System.Threading.Thread.Sleep(100); - _bus.post(SparkTags.SparkTimer, DateTime.Now - start_time); - } - }); - timer_thread.IsBackground = true; - timer_thread.Start(); } #region Public API diff --git a/src/client/spark/Daemons/ThreadedBlackboardDaemon.cs b/src/client/spark/Daemons/ThreadedBlackboardDaemon.cs new file mode 100644 index 000000000..1e852e785 --- /dev/null +++ b/src/client/spark/Daemons/ThreadedBlackboardDaemon.cs @@ -0,0 +1,40 @@ +#nullable enable +namespace Spark.Daemons; + +using bts.api; + +using mbts.spark; +using mbts.ui; + +using System; +using System.Composition; +using System.Threading; + +[Export(typeof(IShellDaemon))] +class ThreadedBlackboardDaemon : IShellDaemon, IDisposable { + readonly Thread thread; + bool isRunning = true; + + [ImportingConstructor] + public ThreadedBlackboardDaemon(IBus bus) { + thread = new(Start) { + IsBackground = true + }; + thread.Start(); + + void Start() { + var interval = TimeSpan.FromMilliseconds(100); + DateTime start_time = DateTime.Now; + Thread.Sleep(interval); + while (isRunning) { + bus.post(SparkTags.SparkTimer, DateTime.Now - start_time); + Thread.Sleep(interval); + } + } + } + + public void Dispose() { + isRunning = false; + thread.Join(); + } +}