Issue reading the output of a process (cipher.exe)

asked 2021-11-22T15:57:29.143+00:00
Tondar 1 Reputation point

Reading output from process works fine. For example I run ping 4.2.2.4 and I can read output live and line by run. But for cipher /w:c: does not show the output until the end of thread.

    Private Sub RunApp()
        Dim Proc As New Process
        AddHandler Proc.OutputDataReceived, AddressOf Proc_OutputDataReceived
        AddHandler Proc.ErrorDataReceived, AddressOf Proc_ErrorDataReceived
        Dim startInfo As New ProcessStartInfo
        With startInfo
            .FileName = "ping"              REM "cipher"
            .Arguments = "4.2.2.4"          REM "/w:c:"
            .RedirectStandardOutput = True
            .RedirectStandardError = True
            .CreateNoWindow = True
            .UseShellExecute = False
        End With
        Proc.StartInfo = startInfo
        Proc.Start()
        Proc.BeginOutputReadLine()
        Proc.BeginErrorReadLine()
    End Sub

    Private Sub Proc_OutputDataReceived(sender As Object, e As DataReceivedEventArgs)
        If e.Data IsNot Nothing AndAlso Not String.IsNullOrEmpty(e.Data) Then
            Console.WriteLine(e.Data)
        End If
    End Sub

    Private Sub Proc_ErrorDataReceived(sender As Object, e As DataReceivedEventArgs)
        If e.Data IsNot Nothing AndAlso Not String.IsNullOrEmpty(e.Data) Then
            Console.WriteLine(e.Data)
        End If
    End Sub

Is there anything I forgot?

VB
VB
An object-oriented programming language developed by Microsoft that is implemented on the .NET Framework. Previously known as Visual Basic .NET.
1,828 questions
{count} votes

1 answer

Sort by: Most helpful
  1. answered 2021-11-22T16:50:25.997+00:00
    Michael Taylor 37,616 Reputation points

    I suspect you're seeing the same behavior in both cases but it just isn't obvious. ping should return back almost instantly so probably by the time your RunApp function gets to the end the other process is already done. cipher on the other hand probably takes a while and so your runapp is finished before it gets done. In either case you are not blocking until the process completes so whoever calls RunApp is potentially running while the other process is still running in the background. If the current process is doing a lot of CPU work or writing to the console then they'll be fighting for resources.

    You might consider switching to an async call and then blocking until the process completes if that is what you want to accomplish.

    Note that console apps can write to the output/error stream however they want. Some processes may buffer calls until the end while others may write as they go along. You have no control over that behavior but running from the command prompt should make this obvious.