有没有办法暂停进程或等到进程完成后再继续下一行代码?
这是我当前压缩所有PDF然后删除的过程。目前,它在压缩之前删除文件已完成。有没有办法暂停/等待过程完成?
Dim psInfo As New System.Diagnostics.ProcessStartInfo("C:\Program Files\7-Zip\7z.exe ", Arg1 + ZipFileName + PathToPDFs)
psInfo.WindowStyle = ProcessWindowStyle.Hidden
System.Diagnostics.Process.Start(psInfo)
'delete remaining pdfs
For Each foundFile As String In My.Computer.FileSystem.GetFiles("C:\Temp\", FileIO.SearchOption.SearchAllSubDirectories, "*.pdf")
File.Delete(foundFile)
Next
你可以使用process.WaitForExit
方法
WaitForExit可以使当前线程等待,直到相关进程退出。
链接:http://msdn.microsoft.com/fr-fr/library/system.diagnostics.process.waitforexit(v=vs.80).aspx
Process.Start返回一个Process实例。正如其他人所提到的,你可以使用WaitForExit()方法,虽然你应该使用WaitForExit(Integer),其中包括一个超时,以防万一与压缩过程出现问题。
所以你的代码会变成:
...
Dim zipper As System.Diagnostics.Process = System.Diagnostics.Process.Start(psInfo)
Dim timeout As Integer = 60000 '1 minute in milliseconds
If Not zipper.WaitForExit(timeout) Then
'Something went wrong with the zipping process; we waited longer than a minute
Else
'delete remaining pdfs
...
End If
有几种WaitForExit方法可用。
WaitForExit()
使当前线程等待,直到相关进程终止。应该在进程上调用所有其他方法之后调用它。要避免阻塞当前线程,请使用Exited事件。
- 指示Process组件无限期地等待关联进程退出。
WaitForExit(Int32)
使当前线程等待,直到相关进程终止。应该在进程上调用所有其他方法之后调用它。要避免阻止当前线程,请使用Exited事件。
- 指示Process组件等待指定的毫秒数,以便关联的进程退出。