From ebb83a6a1e247a7862a42a276e07f42ae3c209cf Mon Sep 17 00:00:00 2001 From: Matt Nadareski Date: Thu, 5 Dec 2024 21:40:53 -0500 Subject: [PATCH] Unify queue handling in processing queue --- CHANGELIST.md | 1 + MPF.Frontend/OldDotNet.cs | 45 +++++++++++++++++++++++++++++++++ MPF.Frontend/ProcessingQueue.cs | 13 +--------- 3 files changed, 47 insertions(+), 12 deletions(-) create mode 100644 MPF.Frontend/OldDotNet.cs diff --git a/CHANGELIST.md b/CHANGELIST.md index db5de725..7c0e0e79 100644 --- a/CHANGELIST.md +++ b/CHANGELIST.md @@ -47,6 +47,7 @@ - Ensure dumping commands are tested - Add tests around default values - Increase sleep time in queue +- Unify queue handling in processing queue ### 3.2.4 (2024-11-24) diff --git a/MPF.Frontend/OldDotNet.cs b/MPF.Frontend/OldDotNet.cs new file mode 100644 index 00000000..825a0980 --- /dev/null +++ b/MPF.Frontend/OldDotNet.cs @@ -0,0 +1,45 @@ +#if NET20 || NET35 +using System.Collections; +using System.Collections.Generic; + +namespace MPF.Frontend +{ + internal interface IReadOnlyCollection : IEnumerable + { + int Count { get; } + } + + internal sealed class ConcurrentQueue : IReadOnlyCollection + { + private Queue _queue = new Queue(); + + private object _lock = new object(); + + public int Count => _queue.Count; + + public void Enqueue(T item) + { + lock (_lock) + { + _queue.Enqueue(item); + } + } + + public bool TryDequeue(out T item) + { + lock (_lock) + { + item = default(T)!; + if (_queue.Count == 0) + return false; + + item = _queue.Dequeue(); + return true; + } + } + + IEnumerator IEnumerable.GetEnumerator() => _queue.GetEnumerator(); + IEnumerator IEnumerable.GetEnumerator() => _queue.GetEnumerator(); + } +} +#endif \ No newline at end of file diff --git a/MPF.Frontend/ProcessingQueue.cs b/MPF.Frontend/ProcessingQueue.cs index 2f7d7c47..24019ce1 100644 --- a/MPF.Frontend/ProcessingQueue.cs +++ b/MPF.Frontend/ProcessingQueue.cs @@ -1,7 +1,5 @@ using System; -#if NET20 || NET35 -using System.Collections.Generic; -#else +#if NET40_OR_GREATER || NETCOREAPP using System.Collections.Concurrent; #endif using System.Threading; @@ -14,11 +12,7 @@ namespace MPF.Frontend /// /// Internal queue to hold data to process /// -#if NET20 || NET35 - private readonly Queue _internalQueue; -#else private readonly ConcurrentQueue _internalQueue; -#endif /// /// Custom processing step for dequeued data @@ -77,17 +71,12 @@ namespace MPF.Frontend continue; } -#if NET20 || NET35 - // Get the next item from the queue and invoke the lambda, if possible - _customProcessing?.Invoke(_internalQueue.Dequeue()); -#else // Get the next item from the queue if (!_internalQueue.TryDequeue(out var nextItem)) continue; // Invoke the lambda, if possible _customProcessing?.Invoke(nextItem); -#endif } } }