/// <summary> /// 按照队列方式执行排队的命令。相对而言,这时候Invoker /// 具有执行的主动性,此处可以嵌入很多其他控制逻辑 /// </summary> public void Run() { while (queue.Count > 0) { VoidHandler handler = queue.Dequeue(); handler(); } }
public void If_there_are_no_unprocessed_commands_dequeue_returns_empty_collection() { const int lastProcessedCommand = 15; var sut = new CommandQueue(SessionFactory); var outstandingCommands = sut.Dequeue(1); Assert.IsFalse(outstandingCommands.Any()); }
private InternalCommand DequeueCommand() { if (!running) { return null; } return commandQueue.Dequeue(); }
public void UnDo() { if (CalcleQueue == null) { CalcleQueue = new Queue <ICMD>(); } ICMD cmd = CommandQueue.Dequeue(); cmd.UnDo(); CalcleQueue.Enqueue(cmd); }
static void Main(string[] args) { if (args.Count() == 0) { OpenFileDialog ofd = new OpenFileDialog() { InitialDirectory = "c:\\", Filter = "Blaze Files (*.blaze)|*.blaze" }; if (ofd.ShowDialog() == DialogResult.OK) { args = new string[] { ofd.FileName }; } else { return; } } string newPath = args[0].Replace(".blaze", ".burn"); Preprocessor.Preprocessor.Fix(args[0], newPath); List <string> lines = File.ReadAllLines(newPath).ToList(); while (running && Line < lines.Count) { while (CommandQueue.Count > 0) { CommandQueue.Dequeue()(); } for (int i = 0; i < Modules.Length; i++) { bool forceContinue = Modules[i].Transform(lines[Line]); while (CommandQueue.Count > 0) { CommandQueue.Dequeue()(); } if (forceContinue) { break; } } Line++; } while (true) { ; } }
void m_Worker_DoWork(object sender, DoWorkEventArgs e) { int exec = 1; while (CommandQueue != null && CommandQueue.Count > 0) { if (e.Cancel) { e.Result = 1; return; } WriteLine("Running command {0}, {1} remaining.", exec++, CommandQueue.Count); StagedCommand command = CommandQueue.Peek(); try { if (command.Pre != null) { command.Pre(); } int result = ShellExec(command.Command); if (command.Post != null) { command.Post(); } if (result != 0) { e.Result = result; return; } else { CommandQueue.Dequeue(); } } catch (Exception exc) { WriteLine("Error: {0}", exc.Message); e.Result = 1; return; } } WriteLine("All commands executed successfully."); e.Result = 0; return; }
public void Update() { if (CommandQueue.Count == 0) { return; } if (CurCommand != null) { return; } CurCommand = CommandQueue.Dequeue(); CoroutineExecuter.StartCoroutine(CurCommand.Execute(CoroutineExecuter)); }
private void ProcessNextCommand() { if (HSTWorkcell.stopRunScript) { HSTWorkcell.stopRunScript = false; if (HSTMachine.Workcell != null) { if (HSTMachine.Workcell.getPanelOperation() != null) { if (HSTMachine.Workcell.getPanelOperation().getOperationStatusPanel() != null) { UIUtility.Invoke(HSTMachine.Workcell.getPanelOperation().getOperationMainPanel(), () => { HSTMachine.Instance.MainForm.getPanelCommand().EnableTestScriptRun(); }); } } } MessageBox.Show("Test Stopped."); } else if (CommandQueue.Count > 0) { //Lai: Testing purpose ExecuteCommand(CommandQueue.Dequeue()); } else { if (HSTMachine.Workcell != null) { if (HSTMachine.Workcell.getPanelOperation() != null) { if (HSTMachine.Workcell.getPanelOperation().getOperationStatusPanel() != null) { UIUtility.Invoke(HSTMachine.Workcell.getPanelOperation().getOperationMainPanel(), () => { HSTMachine.Instance.MainForm.getPanelCommand().EnableTestScriptRun(); }); } } } MessageBox.Show("Test Completed."); } }
public void If_multiple_commands_were_enqueued_it_returns_them_in_FIFO_order() { var fixture = new Fixture(); fixture.Customize(new NumericSequencePerTypeCustomization()); var firstUnique = fixture.Create <int>(); var secondUnique = fixture.Create <int>(); var sut = new CommandQueue(SessionFactory); Enqueue(firstUnique); Enqueue(secondUnique); var lastProcessed = sut.GetLastProcessed(); var uniques = sut.Dequeue(2).Select(x => x.Payload).Cast <TestCommand>().Select(x => x.SomeUniqueProperty).ToList(); CollectionAssert.AreEqual(new[] { firstUnique, secondUnique }, uniques); }
public void When_no_commands_were_processed_it_returns_the_first_command() { var fixture = new Fixture(); var unique = fixture.Create <int>(); var sut = new CommandQueue(SessionFactory); using (var session = SessionFactory.OpenSession()) using (var tx = session.BeginTransaction()) { CommandQueue.Enqueue(new TestCommand(unique), session, DateTime.UtcNow); tx.Commit(); } var lastProcessed = sut.GetLastProcessed(); var command = (TestCommand)sut.Dequeue(1).First().Payload; Assert.AreEqual(unique, command.SomeUniqueProperty); }
public void Update() { if (CommandQueue.Count > 0 && CommandQueue.Peek().GetType() == typeof(MoveCommand)) { if (CommandQueue.Peek().IsFinished) { CommandQueue.Dequeue(); if (CommandQueue.Count > 0) { this.CurrentCommand = CommandQueue.Peek(); } } if (CommandQueue.Count > 0) { Status = CommandQueue.Peek().StatusText; CommandQueue.Peek().Execute(); } } else if (CommandQueue.Count == 0) { Status = "Idle"; } }
private static void Controller() { while (true) { ConsoleKeyInfo input = Console.ReadKey(true); if (input.Key == ConsoleKey.UpArrow) { CommandQueue.Enqueue(Directions.Up); } if (input.Key == ConsoleKey.RightArrow) { CommandQueue.Enqueue(Directions.Right); } if (input.Key == ConsoleKey.LeftArrow) { CommandQueue.Enqueue(Directions.Left); } if (CommandQueue.Count > 2) { CommandQueue.Dequeue(); } } }
/// <summary> /// 需要退出循环 /// </summary> /// <param name="cmdoom"></param> public void Loop(CmdForm cmdoom) { Console.WriteLine("线程循环开始"); while (dataReadyEvent.WaitOne()) { // 循环退出验证 if (ExitCode <= 0) { Console.WriteLine($"ExitCode: {ExitCode}"); break; } // 读取命令 var cmd = ""; lock (CommandQueue) { if (CommandQueue.Count > 0) { cmd = CommandQueue.Dequeue(); } else { continue; } } // 开始执行命令 try { if (cmdoom == null) { Console.WriteLine("CmdForm must be not instantiation!"); return; } ProcessStartInfo startInfo = new ProcessStartInfo(); startInfo.FileName = "cmd.exe"; //设定需要执行的命令 startInfo.Arguments = ""; //“/C”表示执行完命令后马上退出 startInfo.UseShellExecute = false; //不使用系统外壳程序启动 startInfo.RedirectStandardInput = true; //不重定向输入 startInfo.RedirectStandardOutput = true; //重定向输出 startInfo.RedirectStandardError = true; // 重定向错误 startInfo.CreateNoWindow = true; //不创建窗口 var proc = new Process(); proc.StartInfo = startInfo; Console.WriteLine("开启CMD进程"); // 异步委托事件读取错误信息 proc.ErrorDataReceived += new DataReceivedEventHandler(delegate(object sender, DataReceivedEventArgs e) { this.AppendText(cmdoom, e.Data + Environment.NewLine); //Console.WriteLine($"在异步委托读取到的错误信息数据:{e.Data}"); }); proc.OutputDataReceived += new DataReceivedEventHandler(delegate(object sender, DataReceivedEventArgs e) { this.AppendText(cmdoom, e.Data + Environment.NewLine); //Console.WriteLine($"在异步委托读取到的正常信息数据:{e.Data}"); }); proc.Start(); proc.BeginErrorReadLine(); proc.BeginOutputReadLine(); // 读取版权信息 //proc.StandardOutput.ReadLine(); //proc.StandardOutput.ReadLine(); // 输入命令 Console.WriteLine($"开始输入命令:{cmd}"); proc.StandardInput.WriteLine(cmd); //this.AppendText(cmdoom, proc.StandardOutput.ReadLine() + Environment.NewLine); //proc.StandardInput.WriteLine(Environment.NewLine); //var write = proc.StandardOutput.ReadLine(); //this.AppendText(cmdoom, write +Environment.NewLine); Console.WriteLine("命令输入完毕,回车换行"); //string pathPre = write.Substring(0, 2).ToUpper(); //// TODO 该循环是不安全的,输入的命令有问题将会造成死循环 //do //{ // if (proc.StandardOutput.EndOfStream) // { // Console.WriteLine("当前在CMD进程输出流的末尾"); // } // // ReadLine(该函数需要读取到\r\n才会返回,否则会一值等待) 读取输出,因为输入流不能关闭,所以只能自己一行行读取输出 // string logm = proc.StandardOutput.ReadLine()?.Trim() ?? ""; // Console.WriteLine($"读取到的新行:{logm ?? "null"}"); // if (logm.IndexOf(pathPre) != -1) // { // // 此时的logm为在输入命令前的路径 // break; // } // this.AppendText(cmdoom, logm + Environment.NewLine); //} while (true); Console.WriteLine("关闭CMD进程"); //proc.Close(); proc.StandardInput.WriteLine("exit"); // 打开新的进程,比如Python,会卡死CMD进程,导致无法退出 proc.WaitForExit(); proc.Close(); //proc.Kill(); proc.Dispose(); } catch (Exception e) { var oldColor = Console.ForegroundColor; Console.ForegroundColor = ConsoleColor.Red; Console.WriteLine($"Error {e.Message}{Environment.NewLine}{e.StackTrace}"); Console.ForegroundColor = oldColor; } } Console.WriteLine("线程循环结束"); }
public override RobotCommand GetNextMove() { if (CommandQueue != null && CommandQueue.Count > 0 && !Map.IsChanged) { return(CommandQueue.Dequeue()); } CommandQueue = null; var routeFinder = new AStarRouteFinder(Map); // first we try to get to a lambda if (Map.LambdaCount > 0) { var routes = new Dictionary <Queue <RobotCommand>, int>(); foreach (var lambda in Map.Lambdas) { var route = routeFinder.GetRouteTo(lambda); if (route == null) { continue; } var score = route.Count; if (Map.Flooding > 0) // flooding, favor lower lambdas { score += lambda.Y * 10; } if (routeFinder.UsesPortals) { score *= 1000; } else if (routeFinder.PushesRocks) { score *= 100; } else if (routeFinder.DisturbsRocks) { score *= 10; } routes.Add(route, score); } if (routes.Count > 0) { CommandQueue = routes.Aggregate((best, route) => best = route.Value < best.Value ? route : best).Key; } } // if all lambdas are gone, try to get to the lift if (Map.LambdaCount == 0) { CommandQueue = routeFinder.GetRouteTo(Map.Lifts.ElementAt(0)); State = String.Format("Navigating to lift at {0}", Map.Lifts.ElementAt(0)); } // can't get lambas or a lift, wait for falling rocks to stop if (CommandQueue == null) { var temp = Map.Clone(); temp.ExecuteTurn(RobotCommand.Wait); if (temp.IsChanged) { State = String.Format("Waiting for rocks to move"); return(RobotCommand.Wait); } } // try to move a rock as a last ditch effort if (CommandQueue == null) { foreach (var rock in Map.MoveableRocks) { if (Map.Cell.IsValidMove(rock.Left(), rock)) { var route = routeFinder.GetRouteTo(rock.Left()); if (route != null) { CommandQueue = route; CommandQueue.Enqueue(RobotCommand.Right); State = String.Format("Moving rock right at {0}", rock); break; } } else if (Map.Cell.IsValidMove(rock.Right(), rock)) { var route = routeFinder.GetRouteTo(rock.Right()); if (route != null) { CommandQueue = route; CommandQueue.Enqueue(RobotCommand.Left); State = String.Format("Moving rock left at {0}", rock); break; } } else if (Map.Cell.At(rock.Right()).IsEarth()) { var route = routeFinder.GetRouteTo(rock.Right()); if (route != null) { CommandQueue = route; State = String.Format("Clearing rock right at {0}", rock); break; } } else if (Map.Cell.At(rock.Left()).IsEarth()) { var route = routeFinder.GetRouteTo(rock.Left()); if (route != null) { CommandQueue = route; State = String.Format("Clearing rock left at {0}", rock); break; } } else if (Map.Cell.At(rock.Down()).IsTraversible()) { var route = routeFinder.GetRouteTo(rock.Down()); if (route != null) { CommandQueue = route; if (Map.Cell.IsValidMove(rock.Down(), rock.Down().Left())) { CommandQueue.Enqueue(RobotCommand.Left); } else if (Map.Cell.IsValidMove(rock.Down(), rock.Down().Right())) { CommandQueue.Enqueue(RobotCommand.Right); } else { CommandQueue = null; } State = String.Format("Clearing rock bottom at {0} : {1}", rock, rock.Down()); break; } } } } // can't get anywhere or move any rocks, give up if (CommandQueue == null) { State = "Nothing I can do..."; return(RobotCommand.Abort); } return(CommandQueue.Dequeue()); }
private static void Update() { foreach (BaseObject obj in Field) { //наличие объекта if (obj != null) { //-Игрок if (obj.Type == Types.Player) { //--в покое if (obj.DroppedFrames >= 0) { if (obj.Raycast(Directions.Down).Item1.Type == Types.Empty) //проверка на падение { obj.DroppedFrames = (int)eDroppedFrames.PlayerJump; } //есть действие else if (CommandQueue.Count != 0) { if ((obj as Player).lastAction == Directions.Up) //восстановление после прыжка { obj.DroppedFrames = (int)eDroppedFrames.PlayerRecover; (obj as Player).lastAction = Directions.Null; } else { Directions command = CommandQueue.Dequeue(); //действие Types commandResult = obj.Push(command); if (commandResult == Types.Empty) { (obj as Player).lastAction = command; command = Directions.Null; } else if (commandResult == Types.Box) //смещение ящика { //проверка блокировки ящика //проверка блокировки ящика Box box = (Box)obj.Raycast(command).Item1; if ((box.Raycast(Directions.Up).Item1.Type == Types.Empty) && (box.Raycast(command).Item1.Type == Types.Empty)) { if (box.Raycast(Directions.Down).Item1.Type != Types.Empty) { if (box.Push(command) == Types.Empty) { if (obj.Push(command) == Types.Empty) { (obj as Player).lastAction = command; command = Directions.Null; } } } } } } } } //--в задержке else if (obj.DroppedFrames != 0) { obj.DroppedFrames += _frameswindow; if (obj.DroppedFrames == 0) //падение в конце задержки { obj.Push(Directions.Down); } else if (CommandQueue.Count != 0) //управление в прыжке { Directions command = CommandQueue.Dequeue(); //прыжок вбок if ((obj as Player).lastAction == Directions.Up && (command == Directions.Right || command == Directions.Left)) { //возможность прыжка вбок bool raycast_success = false; if (command == Directions.Right && obj.Raycast(Directions.LowerRight).Item1.Type == Types.Box) { raycast_success = true; } else if (command == Directions.Left && obj.Raycast(Directions.LowerLeft).Item1.Type == Types.Box) { raycast_success = true; } if (raycast_success) { Types commandResult = obj.Push(command); if (commandResult == Types.Empty) { obj.DroppedFrames = 0; (obj as Player).lastAction = command; } else if (commandResult == Types.Box) { //проверка блокировки ящика Box box = (Box)obj.Raycast(command).Item1; if ((box.Raycast(Directions.Up).Item1.Type == Types.Empty) && (box.Raycast(command).Item1.Type == Types.Empty)) { if (box.Raycast(Directions.Down).Item1.Type != Types.Empty) { if (box.Push(command) == Types.Empty) { if (obj.Push(command) == Types.Empty) { (obj as Player).lastAction = command; command = Directions.Null; } } } } } } } } } } else if (obj.Type == Types.Box) { //в покое if (obj.DroppedFrames >= 0) { if (obj.Raycast(Directions.Down).Item1.Type == Types.Empty) //проверка на падение { obj.DroppedFrames = (int)eDroppedFrames.Box; } } //в задержке else if (obj.DroppedFrames != 0) { obj.DroppedFrames += _frameswindow; if (obj.DroppedFrames == 0) //падение в конце задержки { obj.Push(Directions.Down); } } } } } }