【发布时间】:2011-03-05 04:06:34
【问题描述】:
我正在考虑尝试从 F# 启动一个进程,等待它完成,但也逐步读取它的输出。
这是正确/最好的方法吗? (在我的情况下,我正在尝试执行 git 命令,但这与问题无关)
let gitexecute (logger:string->unit) cmd =
let procStartInfo = new ProcessStartInfo(@"C:\Program Files\Git\bin\git.exe", cmd)
// Redirect to the Process.StandardOutput StreamReader.
procStartInfo.RedirectStandardOutput <- true
procStartInfo.UseShellExecute <- false;
// Do not create the black window.
procStartInfo.CreateNoWindow <- true;
// Create a process, assign its ProcessStartInfo and start it
let proc = new Process();
proc.StartInfo <- procStartInfo;
proc.Start() |> ignore
// Get the output into a string
while not proc.StandardOutput.EndOfStream do
proc.StandardOutput.ReadLine() |> logger
我不明白 proc.Start() 是如何返回一个布尔值并且足够异步的,我可以逐步将输出从 while 中取出。
不幸的是,我目前没有足够大的存储库 - 或足够慢的机器,无法判断事情发生的顺序......
更新
我尝试了 Brian 的建议,它确实有效。
我的问题有点含糊。我的误解是,我认为 Process.Start() 返回了整个过程的成功,而不仅仅是“开始”,因此我看不出它是如何工作的。
【问题讨论】:
-
我在使用异步工作流完成此类任务时取得了一些成功:stackoverflow.com/questions/2649161/…
-
我实际上不确定这里的问题是什么。您上面的代码是否有效?有什么问题?
-
在我看来,您可以编写 tester.exe,将几行写入 stdout 并刷新,等待两秒钟,再写入两行,...并使用它来测试此代码的行为如你所愿,是吗?
-
@Brian,你是对的,我做到了,而且确实如此。谢谢。
-
@Stringer,很有趣,谢谢。
标签: .net f# synchronous processstartinfo