Why is my WindowsForm not responding while executing loop Why is my WindowsForm not responding while executing loop powershell powershell

Why is my WindowsForm not responding while executing loop


I got the answer now, if anyone runs into the same problem as I have.

First of all, if you just create a GUI and do some processing, they use the same thread. example:

# Windows Form    $window = New-Object System.Windows.Forms.Form$window.text = "Process Watcher"$window.size = New-Object System.Drawing.Size(350,100) $window.location = New-Object System.Drawing.Size(100,100) $window.ShowDialog()# Processingwhile (1) { # Do Stuff }

PowerShell will now show the $window because of the .ShowDialog() method, but the Windows Form ($window) won't be responsive. That's because you're running a loop in the same thread as you show the Windows-Form Dialog.

So we need to create a Background Task for the loop, so it has a thread for itself. That's what PowerShell's Start-Job cmdlet is for.

let's say you're monitoring a process, and want to visualize it in a Windows-Form. Your Code will look like this:

$target = "firefox"# JobStart-Job -argumentlist $target {    param($target)    while ((get-process $target).Responding) {Sleep -Milliseconds 100}    if (!(get-process $target).Responding) {<# Do Stuff #>}}# Windows Form    $window = New-Object System.Windows.Forms.Form$window.text = "Process Watcher"$window.size = New-Object System.Drawing.Size(350,100) $window.location = New-Object System.Drawing.Size(100,100) $window.ShowDialog()

with this code, your Windows-Form is responsible, and your loop is executing in the background. What i also want to show with this code example is, that you have to pass a variable which you declared outside the job scriptblock to the job with the -argumentlist Parameter and param() statement. otherwise it won't work.

I hope this answer will help someone because google doesn't really give a good answer to this (or I just didn't find a good one)