static void Main(string[] args)
{
Process process = null;
CancellationTokenSource cancellationTokenSource = null;
do
{
var command = Console.ReadLine();
if (command == "quit")
break;
if (command == "start")
{
// 创建CancellationTokenSource实例
cancellationTokenSource = new CancellationTokenSource();
var token = cancellationTokenSource.Token;
Task.Run(() =>
{
// 启动一个外部进程
process = new Process();
var procStartInfo = process.StartInfo;
procStartInfo.FileName = "ping.exe";
procStartInfo.Arguments = "127.0.0.1 -n 10";
procStartInfo.RedirectStandardOutput = true;
procStartInfo.RedirectStandardError = true;
procStartInfo.UseShellExecute = false;
procStartInfo.CreateNoWindow = false;
procStartInfo.RedirectStandardInput = true;
process.Start();
while (!process.HasExited)
{
Thread.Sleep(2000);
if (cancellationTokenSource.IsCancellationRequested)
{
Console.WriteLine("close");
process.Kill();
break;
}
}
process.WaitForExit();
var result = process.StandardOutput.ReadToEnd();
Console.WriteLine("over");
Console.WriteLine(result);
}, token);
}
if (command == "cl")
{
if (cancellationTokenSource != null)
{
cancellationTokenSource.Cancel();
}
}
} while (true);
}
进程对象本身没有中断的方法,只能进行关闭,为了能通过命令交互及时中断进程并获取执行中产生的输出,采用异步调用的方式,通过CancellationTokenSource进行取消操作。
进程开启后,通过轮询方式,来响应取消操作,进行进程关闭。关闭进程后,再及时获取输出。