I've created a Windows form where you can click a button that starts a backup process (Using Start-Job
) of about 15 minutes.
I used Start-Job
in order to keep the form responsive during the backup process (By responsive I mean you can move it around, minimize it and so on).
However, I would like the form to pop up a message box once the job is completed and I can't manage to get to the right result.
At first I tried a While
loop that checks every 10 seconds if the job is completed:
$BackupButton.Add_Click( {
$BackupJob = Start-Job -ScriptBlock { ... }
$Completed = $false
while (!($Completed)) {
if ($BackupJob.State -ne "Running") {
$Completed = $true
}
Start-Sleep -Seconds 10
}
[System.Windows.Forms.MessageBox]::Show('Successfully completed the backup process.', 'Backup Tool', 'OK', 'Info')
})
This gave me the message box after the job completed but the form was unresponsive during the process, probably because it was still using the thread's resources for the While
loop.
Then, I tried using Register-ObjectEvent
to call the message box to show when the job's state has changed:
$BackupButton.Add_Click( {
$BackupJob = Start-Job -ScriptBlock { ... }
Register-ObjectEvent $BackupJob StateChanged -Action {
[System.Windows.Forms.MessageBox]::Show('Successfully completed the backup process.', 'Backup Tool', 'OK', 'Info')
}
})
This option did keep the form responsive during the process, but the message box (The event's action block) never started, until the moment I closed the Windows form.
Is there any option that will both make the message box appear on time (Not when the form closes) and not use the form's thread (Keep it responsive)?
Edit: Alternatively, is there a way to control my form from the background job? I tried to send the form's buttons/controls as arguments to the job and then control the form's events from the job but it didn't work. If there's a way to somehow access the form from the background job, this will also solve my problem.
Thanks in advance.