【问题标题】:Read Standard Output and check status of multiple processes VB.NET读取标准输出并检查多个进程 VB.NET 的状态
【发布时间】:2013-10-22 09:33:02
【问题描述】:

我运行多个命令行进程,以循环方式启动它们。它可以工作并异步启动所有这些。

Public Sub DoWork
Dim i As Integer = 0
        While (Args_reader.Peek() > -1)
            i = i + 1
            MyArg = Args_reader.ReadLine
            Dim MyArg As String
            Dim MyProcess(i) As Process
            MyProcess(i) = New Process
            With MyProcess(i).StartInfo
                .FileName = MyFile
                .Arguments = MyArg
                .UseShellExecute = False
                .CreateNoWindow = True
                .RedirectStandardInput = True
                .RedirectStandardOutput = True
                .RedirectStandardError = True
                .WindowStyle = ProcessWindowStyle.Hidden
            End With
            MyProcess(i).Start()
        End While
        Args_reader.Close()
        i = 0
End Sub

我可以读取所有它们的 stdOutput 并检查它们的状态吗? 我需要等到他们完成才能继续执行程序。

【问题讨论】:

    标签: vb.net asynchronous process stdout


    【解决方案1】:

    我建议您在循环内将async 事件分配给every process,以便在该进程有任何输出时触发它们。标准输出或错误输出:

     Dim Proceso As New Process
    
     'Add the event handlers:
    
     AddHandler Proceso.OutputDataReceived, AddressOf CallbackProcesoAsync
     AddHandler Proceso.ErrorDataReceived, AddressOf ErrorDataReceivedAsync
    
     Dim startInfo As New ProcessStartInfo
     startInfo.FileName = execFile
     startInfo.RedirectStandardOutput = True
     startInfo.RedirectStandardError = True
     startInfo.CreateNoWindow = False
     Proceso.StartInfo = startInfo
     Proceso.Start()
    

    异步事件应该是这样的:

     Private Sub CallbackProcesoAsync(sender As Object, args As System.Diagnostics.DataReceivedEventArgs)
    
        If Not args.Data Is Nothing AndAlso Not String.IsNullOrEmpty(args.Data) Then
    
           'args.Data have the output
    
        End If
    
    End Sub
    
    Private Sub ErrorDataReceivedAsync(sender As Object, args As System.Diagnostics.DataReceivedEventArgs)
    
       If Not args.Data Is Nothing AndAlso Not String.IsNullOrEmpty(args.Data) Then
    
           'args.Data have the output
    
       End If
    
    
    End Sub
    

    【讨论】:

    • 是的。看起来很容易。我只是不明白,我怎样才能接收所有进程的输出,我开始循环了。而且我不知道它可能有多少个进程。一切都取决于从文本文件中读取的参数行。可能是什么。我是否必须在回调和错误接收中进行另一个循环?
    • 因为每个进程都会触发异步事件。作为对象的参数 sender 是调用事件的进程,您可以使用 args 参数将其输出。
    • 是的。有用。我可以读取所有流程的所有输出。谢谢你。但。另一个问题,由于某种原因,我如何确定哪个是我需要的过程?例如,如何停止单击按钮的过程?现在我什至无法阻止所有这些。 MyProcess.Kill() MyProcess.Close() MyProcess.Dispose() 不起作用:(
    • 是的!现在工作!再次感谢您。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-02-17
    • 2015-01-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多