2

Just a quick one. I have a problem with a simple tool that I've created that gets the CPU usage for a set amount of time with a small box that appears to display the % of CPU being used (I've stripped out the GUI for the code below).

function loop
{
$get = read-host
for($start = 0; $start -le 100;$start++)
{
cls
$pro_percentage = Get-WmiObject win32_processor -computer $get -property Loadpercentage | select loadpercentage
$percentage = "Processor usage is: " + $pro_percentage.loadpercentage + "%"
$percentage
}
}
loop

There's a few other bits to the GUI that I've created but I've noticed one majour problem, and this goes for other GUI apps that I have created. Whenever the 'go' button is pressed to start the script from the dialog box, the GUI freezes. The menu bar that I've created inside the GUI freezes and no other button can be pressed.

Am I supposed to run each function in a different thread? Something like that?

Thanks

obious
  • 609
  • 8
  • 21
  • 33

1 Answers1

6

Try to add:

[System.Windows.Forms.Application]::DoEvents() 

in your loop. Quick and dirty, however.

Community
  • 1
  • 1
David Brabant
  • 41,623
  • 16
  • 83
  • 111
  • Thanks. Would to mind explaining DoEvents() please? The documentation I've found on the net is limited – obious May 29 '12 at 07:43
  • 1
    DoEvents() flushes out all pending events. So, your UI won't have to do all the pending events that are queued up. Also, the idea thing would be: run this piece of code in a PowerShell background and monitor the job status. – ravikanth May 29 '12 at 09:10
  • Emphasis on *dirty*. A terrible solution all the way around, one almost guaranteed to cause more problems than it solves. – Cody Gray - on strike Feb 08 '16 at 10:54