Why Application.DoEvents make cpu usage raise to 100%
I often use this code in winforms applications to wait for events, without using threads.
while(checkSomething()){
Application.DoEvents();
}
The program and pc is still responsive while the loop run, 开发者_如何学Pythonhowever if I look cpu usage in task managart, it usage is reported as 100% . Do you know why this happens?
Application.DoEvents() checks if there are some events that needs to be processed and then process them, and it returns. If your checkSomething()
doesn't block on anything you have implemented a busy loop.
That is, your processor is busy running Application.DoEvents()
and checkSomething()
as fast as it can.
If your checkSomething is not checking data related to other threads, what are you actually checking for ? - sounds like there's rather an event you should be handling instead of polling.
When you add this:
while(checkSomething()){
Application.DoEvents();
}
You're basically saying to have the program process windows messages, as fast as possible, without anything stopping it until "checkSomething" returns true.
There are a lot of reasons to avoid DoEvents
- that being said, if you really plan to do this, you should try to give up some processing time in your loop:
while(checkSomething()){
Application.DoEvents();
Thread.Sleep(10); // Sleep a tiny amount...
}
Because you're doing what's referred to as "busy waiting" if your checkSomething()
call returns true all the time. The CPU is running your checkSomething()
call. While it evaluates to true
, you will remain in the loop, process events, and do it all over again.
Application.DoEvents is very dangerous. I used to call it to make the UI of my WinForms application responsive, however you can use BackgroundWorker to make the UI responsive with great ease and you will avoid InvokeRequired overhead.
because... whatever it is it does, it does non-stop?
精彩评论