【问题标题】:VB.NET Process BeginOutputReadLine not workingVB.NET 进程 BeginOutputReadLine 不起作用
【发布时间】:2014-08-01 13:37:53
【问题描述】:

我的目标是实时读取 7zip 命令行进程的输出。我编写了一个使用BeginOutputReadLine 的异步输出阅读器。如果发送到输出,此方法应立即返回一个新行。或者,就像 MSDN 所说:When asynchronous read operations start, the event handler is called each time the associated Process writes a line of text to its StandardOutput stream.

这是我的代码

Private Sub StartProcess()
    Dim Proc As New Process

    Proc.StartInfo.FileName = Application.StartupPath & "\7z.exe"
    Proc.StartInfo.WorkingDirectory = "D:\temp"
    Proc.StartInfo.Arguments = "a -t7z ""D:\temp.7z"" -mx=9 -m0=LZMA -ms=on -mhc=on -mmt=on -mtc=off -mta=off -ptest -mhe=off"

    Proc.StartInfo.UseShellExecute = False
    Proc.StartInfo.RedirectStandardOutput = True
    Proc.StartInfo.CreateNoWindow = True

    AddHandler Proc.OutputDataReceived, AddressOf OutputHandler

    Proc.Start()
    Proc.BeginOutputReadLine()
    Proc.WaitForExit()

    Proc.Dispose()
    Proc = Nothing
End Sub

Private Sub OutputHandler(sendingProcess As Object, outLine As DataReceivedEventArgs)
    If Not String.IsNullOrEmpty(outLine.Data) Then
        Console.WriteLine(outLine.Data)
    End If
End Sub

问题是在流程结束之前我没有得到任何线路。之后,所有输出都返回到关联的流OutputHandler。我的异步代码的结果与使用同步StandardOutput.ReadToEnd 方法的结果非常相似。我做错了什么?

[编辑] 我创建了一个批处理文件,用于使用 ping 命令测试我的代码。这似乎行得通! 7zip 的输出有什么奇怪的吗?因为看起来问题与 7zip 的输出有关,而不是与读取它的代码有关。

【问题讨论】:

  • 这是完全正常的,本机程序在重定向时会将其 stdout 流切换到缓冲模式。更高效。在缓冲区已满、程序结束或 C 程序员编写显式 fflush() 调用之前,您什么都看不到。他没有这样做。改用SevenZipSharp 取得成功。
  • 我试过 SevenZipSharp 0.64。它看起来很有希望,但非常有问题。如果你知道一个稳定的库,那么我很想听听。

标签: vb.net asynchronous command-line output 7zip


【解决方案1】:

只需从您的代码中删除 Proc.WaitForExit() - 它会导致您的应用程序等待直到结束。

如果您想知道进程何时退出,请使用另一个 Addhandler 来捕获 Proc.Exited 事件

【讨论】:

    猜你喜欢
    • 2011-11-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-12-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多