在运行外部进程时在VB.net中使用sleep

时间:2014-08-07 20:21:10

标签: python vb.net

我在VB.net中运行Python脚本时遇到问题,因为.net程序会运行CPU使用率。本质上,我从VB.net程序中执行Python脚本,重新定向标准输出,以便Python脚本打印的内容被.net捕获。

                Dim python_handler As New PythonHandler
                python_handler.Execute("python.exe", "my_script.py")

                ' Wait for python_handler to get back data
                While python_handler.pythonOutput = String.Empty

                End While

                Dim pythonOutput As String = python_handler.pythonOutput

这里PythonHandler是一个类,它的Execute函数如下所示:

Public Sub Execute(ByVal filePath As String, ByVal arguments As String)
    If _process IsNot Nothing Then
        Throw New Exception("Already watching process")
    End If
    _process = New Process()
    _process.StartInfo.FileName = filePath
    _process.StartInfo.Arguments = arguments
    _process.StartInfo.UseShellExecute = False
    _process.StartInfo.RedirectStandardInput = True
    _process.StartInfo.RedirectStandardOutput = True
    _process.Start()
    _process.BeginOutputReadLine()
End Sub

Private Sub _process_OutputDataReceived(ByVal sender As Object, ByVal e As System.Diagnostics.DataReceivedEventArgs) Handles _process.OutputDataReceived
    If _process.HasExited Then
        _process.Dispose()
        _process = Nothing
    End If
    RaiseEvent OutputRead(e.Data)
End Sub

Private Sub textProcessing_OutputRead(ByVal output As String) Handles Me.OutputRead
    outputFetched = True
    pythonOutput = output
End Sub

问题是存在While循环,因为它等待Python脚本完成。 CPU最高可达100%。我尝试在While循环中放置一个System.Threading.Thread.Sleep(200),但是.net程序无法捕获Python输出,没有返回任何内容。可能是因为Process.BeginOutputReadLine()是异步的吗?

谢谢。

2 个答案:

答案 0 :(得分:0)

我不知道_process_OutputDataReceived事件被分配到_process.OutputDataReceived的位置。您应该在开始此过程之前分配此项,然后调用_process.WaitForExit()而不是while循环。它应该自动阻止,直到完成该过程。至少我的C#测试确实如此。

_process = New Process()
_process.StartInfo.FileName = filePath
_process.StartInfo.Arguments = arguments
_process.StartInfo.UseShellExecute = False
_process.StartInfo.RedirectStandardInput = True
_process.StartInfo.RedirectStandardOutput = True
AddHandler _process.OutputDataReceived, AddressOf _process_OutputDataReceived
_process.Start()
_process.BeginOutputReadLine()
_process.WaitForExit()

答案 1 :(得分:0)

要扩展Slippery Petes的答案......无论何时使用异步方法,使用轮询循环来等待结果几乎都不正确。以下行非常耗费处理器,并且会影响使用异步方法的性能优势。

While python_handler.pythonOutput = String.Empty
End While

如果您发现自己使用轮询循环,您应该问自己是否有事件驱动方式来处理此问题,或者在这种情况下是等待事件的正确方法。

_process.WaitForExit()
相关问题