private void ReadOutput(TextReader reader) { string?line; while ((line = reader.ReadLine()) != null) { _logStreamWriter !.WriteLine(line); OnReadNewLine(line); if (State == State.Starting) { if (StartedKeywords.Any(s => line.Contains(s))) { State = State.Started; } else if (FailedKeywords.Any(s => line.Contains(s))) { OnStartFailed(); State = State.Stopped; } } } State = State.Stopped; }
protected async Task StartGuardAsync(string argument, ProcessPriorityClass priority = ProcessPriorityClass.Normal) { State = State.Starting; _logFileStream = new FileStream(LogPath, FileMode.Create, FileAccess.Write, FileShare.Read, 4096, true); _logStreamWriter = new StreamWriter(_logFileStream) { AutoFlush = true }; Instance.StartInfo.Arguments = argument; Instance.Start(); Global.Job.AddProcess(Instance); if (priority != ProcessPriorityClass.Normal) { Instance.PriorityClass = priority; } if (RedirectOutput) { ReadOutputAsync(Instance.StandardOutput).Forget(); ReadOutputAsync(Instance.StandardError).Forget(); if (!StartedKeywords.Any()) { // Skip, No started keyword State = State.Started; return; } // wait ReadOutput change State for (var i = 0; i < 1000; i++) { await Task.Delay(50); switch (State) { case State.Started: OnStarted(); return; case State.Stopped: await StopGuardAsync(); OnStartFailed(); throw new MessageException($"{Name} 控制器启动失败"); } } await StopGuardAsync(); throw new MessageException($"{Name} 控制器启动超时"); } }