Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does Process.WaitForExit block even though I have it in a separate thread?

C# 3.5 Winforms app.

I have a timer that fires every 30 seconds on separate thread (all it does is write a string of text to the VS output window).

I also have another thread that waits for a certain process to end if it starts up. For example winword.exe.

In that thread I have this code:

p.WaitForExit();

And it will sit there and wait for winword.exe to exit. That works fine.

However, while it is sitting there waiting for winword.exe to exit, the 30 second timer on a completely separate thread (that sends text to the output window) never runs.

If I wait 3 minutes (so the other timer should of run 6 times at this point, but it does not while WaitForExit() is waiting), and then I exit winword.exe; all of sudden my other timer starts running 6 times at once. It is like there is a backlog of the timer event and all of a sudden .Net wants to run it all at the same time.

Why does p.WaitForExit() seem to block my whole application even though I have it executing from a separate thread in my app (not the main UI thread)?

Edit: Yes it is in a separate thread. Here is the code that I use to launch it:

        try
        {
            Thread t = new Thread(ProcessCheck); // Kick off a new thread
            t.Start();

            ConfigLogger.Instance.LogInfo("++ ProcessCheck thread started @ " + DateTime.Now);
        }
        catch (Exception ipwse)
        {
            ConfigLogger.Instance.LogInfo(ipwse.Message + " " + ipwse.StackTrace);
        }



Here is the ProcessCheck() method that I have:

foreach (Process p in System.Diagnostics.Process.GetProcessesByName("winword"))
{
    this.Invoke(new MethodInvoker(delegate()
    {                                                                                 
        try
        {
            p.WaitForExit();
        }
        catch (Exception)
        {

        }
    }));
}
like image 744
fraXis Avatar asked Sep 16 '25 12:09

fraXis


1 Answers

this.Invoke, if done from a WinForms form, will block the UI thread until the process has exited. If the Timer is System.Windows.Forms.Timer, the Tick event is raised on the UI thread. If the UI thread is blocked, that would explain why the Tick event is never raised.

like image 67
Peter Ritchie Avatar answered Sep 18 '25 09:09

Peter Ritchie



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!