From dd071bd8e9180149874ce653c7367c2dd4dc6e02 Mon Sep 17 00:00:00 2001 From: CptMoore <39010654+cptmoore@users.noreply.github.com> Date: Wed, 4 Dec 2024 02:47:31 +0100 Subject: [PATCH] Added volatile to LightWeightBlockingQueue where appropriate and smaller cleanups. --- ModTek/Features/Logging/LightWeightBlockingQueue.cs | 13 ++++++------- 1 file changed, 6 insertions(+), 7 deletions(-) diff --git a/ModTek/Features/Logging/LightWeightBlockingQueue.cs b/ModTek/Features/Logging/LightWeightBlockingQueue.cs index 9e9b4b87..743308ba 100644 --- a/ModTek/Features/Logging/LightWeightBlockingQueue.cs +++ b/ModTek/Features/Logging/LightWeightBlockingQueue.cs @@ -11,11 +11,10 @@ internal class LightWeightBlockingQueue private readonly ConcurrentQueue _queue = new(); private const int MaxQueueSize = 100_000; // probably about 30MB if full - private long _queueSize; // faster than calling _queue.Count - private bool _addingCompleted; // some way to shut down the thread + private volatile int _queueSize; // faster than calling _queue.Count + private volatile bool _addingCompleted; // some way to shut down the thread // returns false if nothing can be dequeued anymore (empty + _addingCompleted) - // [MethodImpl(MethodImplOptions.AggressiveInlining)] internal bool TryDequeueOrWait(out T item) { var spinWait = new SpinWait(); @@ -25,7 +24,7 @@ internal bool TryDequeueOrWait(out T item) { // this can still drop logs, very unlikely but possible Thread.Sleep(1); - if (_queue.IsEmpty) + if (_queueSize == 0) { return false; } @@ -38,7 +37,6 @@ internal bool TryDequeueOrWait(out T item) } // returns false if nothing can be enqueued anymore (_addingCompleted) - // [MethodImpl(MethodImplOptions.AggressiveInlining)] internal bool TryEnqueueOrWait(T item) { if (_addingCompleted) @@ -49,14 +47,15 @@ internal bool TryEnqueueOrWait(T item) while (_queueSize >= MaxQueueSize) { Thread.SpinWait(4); - + if (_addingCompleted) { return false; } } - + // a compare exchange + retries in the loop would be more strict, but going over max is ok too (and faster) Interlocked.Increment(ref _queueSize); + _queue.Enqueue(item); return true; }