从进程异步读取被暂停

时间:2019-12-07 20:24:15

标签: vb.net

我在vb.net中制作了一个应用程序,该应用程序在后台启动了一个类似cmd的进程,异步读取其输出,并将其重定向到文本框中。通常,我的应用程序应实时显示文本框中的每个新输出行。不幸的是,发生了什么事

这些是文本框中显示的第一行输出。 screenshot 1

几秒钟后,由于某种原因发生了不必要的暂停。即使该过程有输出,文本框中也不会显示新行。几分钟后,由于暂停,我看不到所有输出,出现,然后再次出现暂停。 screenshot 2

最后,最后一行显示,该过程终止。 screenshot 3

这是我的代码:

Private Sub StartSteamCMD()
    Try
        Dim psi As ProcessStartInfo = New ProcessStartInfo("cmd.exe", "/C steamcmd +runscript " + temp + "Setti_SRCDS_Manager\install_update.txt")
        With psi
            .UseShellExecute = False
            .RedirectStandardInput = True
            .RedirectStandardOutput = True
            .RedirectStandardError = True
            .CreateNoWindow = True
            .StandardOutputEncoding = Encoding.GetEncoding(CultureInfo.CurrentUICulture.TextInfo.OEMCodePage)
            .StandardErrorEncoding = Encoding.GetEncoding(CultureInfo.CurrentUICulture.TextInfo.OEMCodePage)
        End With
        process = New Process With {.StartInfo = psi}
        AddHandler process.OutputDataReceived, AddressOf Async_Data_Received
        AddHandler process.ErrorDataReceived, AddressOf Async_Data_Received
        process.Start()
        process.BeginOutputReadLine()
        process.BeginErrorReadLine()
    Catch ex As Exception
        MessageBox.Show(ex.Message)
    End Try
End Sub


Private Sub Async_Data_Received(sender As Object, e As DataReceivedEventArgs)
    Try
        Invoke(New InvokeWithString(AddressOf Sync_Output), e.Data)
    Catch ex As Exception
        MessageBox.Show(ex.Message)
    End Try
End Sub


Private Sub Sync_Output(text As String)
    Try
        TextBox1.AppendText(text + Environment.NewLine)
        TextBox1.ScrollToCaret()
        If Not String.IsNullOrEmpty(text) Then
            If text.Contains("downloading") Or text.Contains("validating") Then
                <code to animate the progress bar here>
            ElseIf text.Contains("Success") Then
                <the server is installed successfully, some code to run here>
            ElseIf text.IndexOf("error", 0, StringComparison.CurrentCultureIgnoreCase) > -1 Then
                <some code to run in case of error>
            End If
        End If
    Catch ex As Exception
        MessageBox.Show(ex.Message)
    End Try
End Sub

有什么想法会导致这些停顿?我一直在思考以下内容。正如您在第一个屏幕截图中看到的那样,最后两行是关于与Steam服务器建立连接(从中下载游戏服务器文件的位置)并等待用户信息。也许那一刻该过程在几秒钟内没有产生任何输出。因此,在那几秒钟的某个时间点,会发生异步读取的第一个暂停。然后,该过程再次开始产生输出,但是由于暂停而没有重定向到文本框。可能是由于该过程几秒钟未产生任何输出而使异步读取暂停了吗?

我不知道该怎么想。我厌倦了在互联网上寻找解决方案,因为我找不到关于我的问题的帖子,至少找不到类似的帖子。我希望你们能帮助我。预先感谢

0 个答案:

没有答案