namespace OECS; /// /// A FIFO queue of instances with deferred execution. /// /// Commands are executed in the order they were enqueued. If a command's /// throws, the exception is caught and stored; /// remaining commands continue to execute. /// /// Commands enqueued during are processed in the /// same drain cycle — the queue keeps draining until empty. /// public class CommandQueue { private readonly List _commands = new(); private readonly List _errors = new(); /// /// Number of commands currently waiting in the queue. /// public int Count => _commands.Count; /// /// Exceptions thrown by commands during the most recent call. /// Cleared at the start of each drain cycle. /// public IReadOnlyList Errors => _errors; /// /// Adds a command to the end of the queue. /// public void Enqueue(ICommand command) { _commands.Add(command); } /// /// Executes all queued commands in FIFO order against the given world. /// /// The queue is fully drained — commands enqueued by other commands during /// this call are also executed before the method returns. /// public void ExecuteAll(World world) { _errors.Clear(); int index = 0; while (index < _commands.Count) { var command = _commands[index]; index++; try { command.Execute(world); } catch (Exception ex) { _errors.Add(ex); } } _commands.Clear(); } /// /// Clears all queued commands without executing them. /// public void Clear() { _commands.Clear(); _errors.Clear(); } }