【发布时间】:2017-09-11 15:25:49
【问题描述】:
我有以下来自答案的代码:Process.start: how to get the output?
static void runCommand() {
//* Create your Process
Process process = new Process();
process.StartInfo.FileName = "cmd.exe";
process.StartInfo.Arguments = "/c DIR";
process.StartInfo.UseShellExecute = false;
process.StartInfo.RedirectStandardOutput = true;
process.StartInfo.RedirectStandardError = true;
//* Set your output and error (asynchronous) handlers
process.OutputDataReceived += new DataReceivedEventHandler(OutputHandler);
process.ErrorDataReceived += new DataReceivedEventHandler(OutputHandler);
//* Start process and handlers
process.Start();
process.BeginOutputReadLine();
process.BeginErrorReadLine();
process.WaitForExit();
}
static void OutputHandler(object sendingProcess, DataReceivedEventArgs outLine) {
//* Do your stuff with the output (write to console/log/StringBuilder)
Console.WriteLine(outLine.Data);
}
在我的情况下,我需要同时调用多个实例,我正在考虑制作线程,但我知道这段代码不需要线程。有人可以解释一下区别吗?如果有必要让线程进行异步调用?
提前致谢。亲切的问候
【问题讨论】:
-
I understand that there is no need of threads with this code那么,既然你明白了,为什么还要问这个问题呢? -
因为我不明白其中的区别。感谢您的帮助。
-
如果你不明白其中的区别,那你为什么说你明白其中的区别呢?
-
感谢您的帮助。
-
Process类本质上是异步的,因为您启动的进程完全独立于您自己的进程。如果您重定向输出,它不再是完全独立的,但是异步处理 I/O 是有据可查的,包括TextReader。唯一剩下的是进程退出通知,您可以通过检测输出流的结束(即StandardOutput.ReadLineAsync()和StandardError.ReadLineAsync()都返回null)来实现,或者用TaskCompletionSource包装Exited(见标记的重复)。
标签: c# multithreading shell console delegates