0

What I have:

Dim test As Process = Process.Start("powershell.exe", "-executionpolicy
remotesigned -file C:\temp\test.ps1")

test.WaitForExit()

Finally while wait for "test" to exit, my GUI freezes. How to make it smooth?

hannir
  • 95
  • 1
  • 10

2 Answers2

4

You could use a BackgroundWorker to run this code on a separate thread, currently you are running it on the UI thread which causes it to freeze.

This should get you started:

Private Sub startWorker()
    Dim powershellWorker As New BackgroundWorker
    AddHandler powershellWorker.DoWork, AddressOf doWork

    powershellWorker.RunWorkerAsync()
End Sub

Private Sub doWork(ByVal sender As Object, ByVal e As DoWorkEventArgs)
    Dim test As Process = Process.Start("powershell.exe", "-executionpolicy remotesigned -file C:\temp\test.ps1")
    test.WaitForExit()
End Sub
Nathan
  • 227
  • 3
  • 15
  • Good idea anyway :) The problem now is that I wanna change an textbox.text in the background worker. It gives me " Invalid thread -border operation" as an error (translated with google). Can u help me there too? Thx alot btw for u help ;) – hannir Jul 06 '16 at 17:44
  • Sure, ask a new question and me or someone else will try to help you there. – Nathan Jul 07 '16 at 08:24
1

The test.WaitForExit() is a blocking method and it will block your UI thread. Try running the code in a parallel task and await it

 Dim task As Task = Task.Run(Sub()
     Dim test As Process = Process.Start("powershell.exe", "-executionpolicy remotesigned -file C:\temp\test.ps1")
     Process.WaitForExit()
     Return test
  End Sub)
 Dim test2 As Process = Await task
 // some code that will execute after the process completes

You might need to add the async key word to outer method declaration.

Please note that I am a C# person :-)

honzajscz
  • 2,850
  • 1
  • 27
  • 29
  • 2
    You never call `Process.WaitForExit()`. This will only wait for the code being executed (which is done in no-time). Create a task instead in which you only run `Process.WaitForExit()`. – Visual Vincent Jul 01 '16 at 13:29
  • I have forgotten to add that line there. Now it is better. Thx – honzajscz Jul 01 '16 at 17:36