我知道如何生成一个新进程来执行任意数量的任务,但是我想在一个bash
/ cmd.exe
中执行它们。
问题是,当然我不知道它何时完成,因为WaitForExit()
永远不会发生(bash可以永远运行)。
然而,也许有可能知道StandardInput.WriteLine()
何时可用,以便我知道bash已完成任务并且我可以执行下一个,或者如果最后一个完成 - 关闭bash。< / p>
完整代码(Fiddle)
using System;
using System.Collections.Generic;
using System.Diagnostics;
namespace ProcessExample
{
class Program
{
static void Main(string[] args)
{
var commands = new List<string> { "dir", "cd C:/", "dir" };
var startInfo = new ProcessStartInfo
{
FileName = "cmd.exe",
UseShellExecute = false,
RedirectStandardOutput = true,
RedirectStandardError = true,
RedirectStandardInput = true,
CreateNoWindow = true
};
using (var process = Process.Start(startInfo))
{
commands.ForEach(command => { process.StandardInput.WriteLine(command); });
process.BeginOutputReadLine();
process.BeginErrorReadLine();
process.ErrorDataReceived += (object sender, DataReceivedEventArgs e) => { Console.WriteLine(e.Data); };
process.OutputDataReceived += (object sender, DataReceivedEventArgs e) => { Console.WriteLine(e.Data); };
process.WaitForExit(); // This never happends.
}
Console.ReadLine();
}
}
}