Click here to Skip to main content
15,887,746 members
Please Sign up or sign in to vote.
3.33/5 (3 votes)
See more:
Hi
I've following sittuation. One app is used to set up data for multiple calculations using another app. So for now it do it like that:
Read input data
setup child process P
while p.HasExited = false
   if killProcess = true Then kill process and exit
   Application.DoEvents()

It works but the loop is consuming 50% CPU

I could use WaitForExit but it blocks the UI so probably I need to put it in Background worker.
Do you know any other way to solve this?
Posted

Did you try Process.Exited event?
Just add a handler to that event just before starting your child process.

By the way: never use Application.DoEvents. You might have some unpredictable behaviors...
 
Share this answer
 
v2
Comments
Sergey Alexandrovich Kryukov 21-Mar-11 7:22am    
This is good enough, too, async. version of my variant (please see my Answer).
--SA
Sergey Alexandrovich Kryukov 21-Mar-11 7:23am    
OP commented:

Big thanks. I forgot about this. :(
Olivier Levrey 21-Mar-11 7:25am    
Thank you. I just forgot to warn about the Application.DoEvents...
Of course. (You must be using Dual Core CPU, otherwise it would be 100%.) As a rule of thumb, never use Application.DoEvents and never use spin wait (waiting with loop). Use a separate thread and a blocking call System.Diagnostics.Process.WaitForExit. The thread will be kept in a wait state using zero CPU time until awaken. This is done at the level of CPU. The calling thread switched off and never scheduled again until the process finished. Then the thread is awaken and immediately continue execution (well, more exactly, scheduled for execution very quickly, depending on the priorities of these and competing threads).

—SA
 
Share this answer
 
Comments
Pawel Gielmuda 21-Mar-11 7:24am    
But WaitForExit blocks the UI of parent process. I know that I shouldn't use spin loop ;) (the app is taken from VB6 and I guess there wasn't better choice at that time)
Sergey Alexandrovich Kryukov 21-Mar-11 7:31am    
It should block!!! Therefore, do it in a non-UI thread. Please, read the answer properly.
--SA
Olivier Levrey 21-Mar-11 8:15am    
SA advised to use WaitForExit in a different thread. If you call that function in your main thread (the UI one), you will block the UI. But if you create another thread, and call WaitForExit from this new thead, then your UI will not be blocked (only the other thread will be).
Olivier Levrey 21-Mar-11 7:26am    
Good advices and explanations. My 5.
Sergey Alexandrovich Kryukov 21-Mar-11 7:32am    
Thank you very much. Probably, this explanation is not so good, as OP did not understand. :-)
Maybe you know what to say?
--SA

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900