正如这里所讨论的,ProcessStartInfo 挂在“WaitForExit”上?为什么?- 使用大输出调用 p.WaitForExit() 会填充 OutputStream 并导致死锁,因为进程和输出流相互等待。
我的代码例如:
Dim p = New Process()
Dim ReturnValue As Boolean = False
p.StartInfo = New ProcessStartInfo(LynxPath, "-dump -nolist -width 1000 " & HtmlBuffer)
p.StartInfo.WorkingDirectory = WorkingRoot
p.StartInfo.UseShellExecute = False
p.StartInfo.RedirectStandardOutput = True
p.StartInfo.RedirectStandardError = True
p.StartInfo.WindowStyle = ProcessWindowStyle.Hidden
p.StartInfo.CreateNoWindow = True
p.Start()
ReturnValue = p.WaitForExit(5000)
当处理来自 LYNX 的大量输出时,除非我使用上述超时,否则线程会挂起,并且当输出缓冲区变满时会修剪输出——这意味着我读取的任何输出都不完整。
上面问题中发布的 c# 解决方案似乎通过利用 OutputDataReceived
进程类上的事件来解决这个问题。然而,我的问题是将 c# 代码转换为 vb.net 3.5,我通过正常的转换路线运行它并吐出:
Using process As New Process()
process.StartInfo.FileName = filename
process.StartInfo.Arguments = arguments
process.StartInfo.UseShellExecute = False
process.StartInfo.RedirectStandardOutput = True
process.StartInfo.RedirectStandardError = True
Dim output As New StringBuilder()
Dim [error] As New StringBuilder()
Using outputWaitHandle As New AutoResetEvent(False)
Using errorWaitHandle As New AutoResetEvent(False)
process.OutputDataReceived += Function(sender, e)
If e.Data Is Nothing Then
outputWaitHandle.[Set]()
Else
output.AppendLine(e.Data)
End If
End Function
process.ErrorDataReceived += Function(sender, e)
If e.Data Is Nothing Then
errorWaitHandle.[Set]()
Else
[error].AppendLine(e.Data)
End If
End Function
process.Start()
process.BeginOutputReadLine()
process.BeginErrorReadLine()
' Process completed. Check process.ExitCode here.
If process.WaitForExit(timeout) AndAlso outputWaitHandle.WaitOne(timeout) AndAlso errorWaitHandle.WaitOne(timeout) Then
' Timed out.
Else
End If
End Using
End Using
End Using
然而,Visual Studio 2008 将函数声明标记为无效语法(我认为像这样的内联方法在 4.5 及更高版本中?),如何在 3.5 中使用这个示例 - 无法完全理解它。
编辑:刚刚找到这个链接:http: //msdn.microsoft.com/en-us/library/system.diagnostics.process.outputdatareceived.aspx - 现在想弄清楚