123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137 |
- using System.Collections.Concurrent;
- using System.Diagnostics;
- namespace etoy
- {
- class ConfigurePileline
- {
- ConcurrentQueue<Command> _commands;
- ConcurrentQueue<Command> _completeds;
- Thread _thread;
- int _total;
- Stopwatch _cmdStopwatch;
- int _top;
- public ConfigurePileline(IEnumerable<Command> commands)
- {
- _commands = new ConcurrentQueue<Command>(commands);
- _total = _commands.Count;
- _completeds = new ConcurrentQueue<Command>();
- _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();
- }
- }
- }
- }
|