首页 > 解决方案 > 进程的异步读取被暂停

问题描述

我在 vb.net 中创建了一个应用程序,它在后台启动类似 cmd 的进程,异步读取其输出并将其重定向到文本框中。通常我的应用程序应该实时显示文本框中的每个新输出行。不幸的是,会发生以下情况:

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

几秒钟后,由于某种原因出现了不需要的暂停。即使进程有输出,文本框中也不会显示新行。几分钟后,由于暂停而我看不到的所有输出显示出来,然后再次出现暂停。 截图 2

最后,最后一行出现,进程终止。 截图 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 服务器(下载游戏服务器文件的地方)的连接并等待用户信息。也许那一刻该过程在几秒钟内没有产生任何输出。因此,在那几秒钟内的某个时刻,异步读取的第一次暂停发生了。然后该过程再次开始产生输出,但由于暂停,它没有重定向到文本框。可能是因为该过程几秒钟没有产生任何输出而导致异步读取暂停?

我不知道还能怎么想。我厌倦了在互联网上搜索解决方案,因为我找不到任何关于我的问题或至少类似问题的帖子。我希望你们能帮助我。提前致谢

标签: vb.net

解决方案


推荐阅读