From fd4022ba843d3be83de513feb96ec61f33992cbe Mon Sep 17 00:00:00 2001 From: Matt Nadareski Date: Mon, 29 Mar 2021 10:23:34 -0700 Subject: [PATCH] Add ProcessingQueue (nw) --- MPF.Library/Utilities/ProcessingQueue.cs | 46 ++++++++++++++++++++++++ 1 file changed, 46 insertions(+) create mode 100644 MPF.Library/Utilities/ProcessingQueue.cs diff --git a/MPF.Library/Utilities/ProcessingQueue.cs b/MPF.Library/Utilities/ProcessingQueue.cs new file mode 100644 index 00000000..83edca3b --- /dev/null +++ b/MPF.Library/Utilities/ProcessingQueue.cs @@ -0,0 +1,46 @@ +using System; +using System.Collections.Concurrent; +using System.Threading.Tasks; + +namespace MPF.Utilities +{ + internal class ProcessingQueue + { + /// + /// Internal queue to hold data to process + /// + private readonly ConcurrentQueue InternalQueue; + + /// + /// Custom processing step for dequeued data + /// + private readonly Action CustomProcessing; + + public ProcessingQueue(Action customProcessing) + { + this.InternalQueue = new ConcurrentQueue(); + this.CustomProcessing = customProcessing; + Task.Run(() => ProcessQueue()); + } + + /// + /// Process + /// + private void ProcessQueue() + { + while (true) + { + // Nothing in the queue means we get to idle + if (InternalQueue.Count == 0) + continue; + + // Get the next item from the queue + if (!InternalQueue.TryDequeue(out T nextItem)) + continue; + + // Invoke the lambda, if possible + this.CustomProcessing?.Invoke(nextItem); + } + } + } +}