using System.Collections.Concurrent; using System.Diagnostics; namespace etoy { class ConfigurePileline { ConcurrentQueue _commands; ConcurrentQueue _completeds; Thread _thread; int _total; Stopwatch _cmdStopwatch; int _top; public ConfigurePileline(IEnumerable commands) { _commands = new ConcurrentQueue(commands); _total = _commands.Count; _completeds = new ConcurrentQueue(); _cmdStopwatch = new Stopwatch(); InitThread(); } public void Run() { _thread.Start(); } void InitThread() { _thread = new Thread(OnRunThread); } void ProgressBar(ICommand cmd) { Console.SetCursorPosition(0, _top); Console.Write(new string(' ', Console.WindowWidth)); Console.SetCursorPosition(0, _top); var str1 = new string('#', (int)(50 * cmd.Progress)); var str2 = new string(' ', 50 - (int)(50 * cmd.Progress)); float progress = 100 * (cmd.Progress > 0.999f ? 1 : cmd.Progress); string cost = $"耗时:{_cmdStopwatch.ElapsedMilliseconds}ms"; Console.ForegroundColor = ConsoleColor.Blue; Console.Write(string.Format(">> [{0}{1}] {2:f2}% {3}", str1, str2, progress, cost)); Console.ForegroundColor = ConsoleColor.White; } void OnRunThread(object obj) { Stopwatch sw = new Stopwatch(); sw.Start(); bool success = true; Console.WriteLine(">> 开始执行"); Console.WriteLine(); while (_commands.TryPeek(out var command)) { if (command is ICommand cmd) { _top = Console.CursorTop; if (cmd.Done) { _cmdStopwatch.Stop(); ProgressBar(cmd); Console.WriteLine(); if (_commands.TryDequeue(out var completedCommand)) _completeds.Enqueue(completedCommand); } else { try { if (!cmd.Start) { Console.WriteLine($">> 步骤 ({_completeds.Count + 1}/{_total}) [{command.Description}]"); _cmdStopwatch.Restart(); cmd.Execute(); } else { if (cmd.Exception != null) throw cmd.Exception; ProgressBar(cmd); } } catch (Exception e) { Console.ForegroundColor = ConsoleColor.Red; Console.WriteLine(); Console.WriteLine($"## CMD异常 Type:{cmd.GetType()}\nMessage:{e.Message}"); Console.ForegroundColor = ConsoleColor.White; success = false; break; } } } Thread.Sleep(5); } sw.Stop(); Console.WriteLine(); if (success) { Console.ForegroundColor = ConsoleColor.Green; Console.WriteLine($">> 执行成功. 总耗时: {sw.ElapsedMilliseconds} ms"); Console.ForegroundColor = ConsoleColor.White; } else { Console.ForegroundColor = ConsoleColor.Red; Console.WriteLine($">> 执行失败. "); Console.ForegroundColor = ConsoleColor.White; //输入enter键才关闭控制台 Console.ReadLine(); } } } }