Reputation: 2510
I am trying to enter a 10 second wait in order to execute a command in my script.
The problem is that when I run start-sleep my interface flickers or blocks the window.
I tried to do a special function without using start-sleep but the same thing happens.
First solution (Freeze/Block interaction windows)
if ($Timeout -gt 0) {
Start-Sleep -seconds $Timeout
}
Second solution (Freeze/Block interaction windows)
if ($Timeout -gt 0) {
Timeout $Timeout
}
function Timeout($seconds) {
$doneDT = (Get-Date).AddSeconds($seconds)
while($doneDT -gt (Get-Date)) {
$secondsLeft = $doneDT.Subtract((Get-Date)).TotalSeconds
write-host $secondsLeft
}
}
How could I do to timeout code execution without freezing my winforms?
Thank you
Upvotes: 1
Views: 2812
Reputation: 2676
I would suggest you to do a Background Job using Start-Job
(easiest) or Runspace (a little hard to do but efficient) for your task so u do not have to rely on the sleep timer to make sure ur command completed. But that is your prerogative.
However, you can use this neat little trick although not ideal, to counter your non-responsive form problem. Use the below block to introduce the 10s delay.
for ($i = 0; $i -lt 50; $i++)
{
Start-Sleep -Milliseconds 200
[System.Windows.Forms.Application]::DoEvents()
}
EDIT: Including suggestions.
Sure you can do this inside WinForms. I have done this before. I just moved onto Runspaces
later for reasons of efficiency and resources. But for simple purposes, Start-Job
is the easiest way to go.
$ScriptBlock = {
#super lengthy code enclosed in paranthesis to create a scriptblock
#say takes a large amount of time to complete
}
$myJob = Start-Job -ScriptBlock $ScriptBlock
Do
{
Start-Sleep -Milliseconds 100
[System.Windows.Forms.Application]::DoEvents()
}
While ($myJob.State -ne "Completed")
$myJob | Receive-Job
Now you can include contingencies for when the job fails and stuff, but I will let u figure that out.
Upvotes: 1