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); + } + } + } +}