I am fighting with a problem in my PowerShell 4.0 script. I constructed a user interface using the windows Forms namespace but need to do some time consuming processing which is why I adopted for a BackgroundWorker
to keep my GUI responsive.
Once I started I used the $Worker.Add_DoWork({})
method to add an event subscription but this does not work. That is why I used the Register-ObjectEvent
instead. Now my DoWork
event is only executed once I close my Form and I don't get why this is happening. My code is below, can anyone help me with this issue?
#Create worker object
$Worker = new-object System.ComponentModel.BackgroundWorker;
$Worker.WorkerReportsProgress = $true;
#Handles $Worker.ReportProgress event
$ReportProgress = {$Progressbar.PerformStep()};
#Handles $Worker.DoWork event
$DoWork = { write-host("do work event fired")};
#Add eventhandlers
Register-ObjectEvent -InputObject $Worker -EventName DoWork -Action $DoWork ;
Register-ObjectEvent -InputObject $Worker -EventName ProgressChanged -Action $ReportProgress;
If I call the $Worker.RunWorkerAsync()
method in my script, no output is generated. If I close my form which called the $Worker.RunWorkerAsync()
method the text "Do work event fired" is output into the PowerShell console.