using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; namespace StardewModdingAPI.Framework { /// A thread-safe command queue optimized for infrequent changes. internal class CommandQueue { /******** ** Fields ********/ /// The underlying list of queued commands to parse and execute. private readonly List RawCommandQueue = new(); /******** ** Public methods ********/ /// Add a command to the queue. /// The command to add. public void Add(string command) { lock (this.RawCommandQueue) this.RawCommandQueue.Add(command); } /// Remove and return all queued commands, if any. /// The commands that were dequeued, in the order they were originally queued. /// Returns whether any values were dequeued. [SuppressMessage("ReSharper", "InconsistentlySynchronizedField", Justification = "Deliberately check if it's empty before locking unnecessarily.")] public bool TryDequeue([NotNullWhen(true)] out string[]? queued) { if (this.RawCommandQueue.Count is 0) { queued = null; return false; } lock (this.RawCommandQueue) { queued = this.RawCommandQueue.ToArray(); this.RawCommandQueue.Clear(); return queued.Length > 0; } } } }