Using Visual Studio Version 17.12.3
C# Winforms with .Net Framework 4.8.1
I am building the installation process for my application. In this particular situation, I need to spawn a process to run the installer for the database provider based on the user's selection. I would like to have the shelled application complete and return cotrol to the install process.
I followed the document "Use Visual C# to wait for a shelled application to finish" on the Microsoft site. What I am experiencing is the line p.WaitForExit() does not wait, the code will continue. I have tried placing a wait value of varying size with no affect.
This is the first time I have tried this and not quite sure if I am doing the right thing oe is there a better way to accomplish this.
Here is the code snip in question. This is enclosed in a Try/Catch.
string sysFolder = Environment.GetFolderPath(Environment.SpecialFolder.System);
ProcessStartInfo pInfo = new ProcessStartInfo();
pInfo.FileName = sysFolder + @"\notepad.exe";
Process p = Process.Start(pInfo);
p.WaitForInputIdle();
p.WaitForExit();
if (p.HasExited == false)
{ p.WaitForExit(5000); }
return p.ExitCode == 0;
Jaish MathewsPosted Dec 22, 2024, 4:07 AM
The
Process.WaitForExitmethod should normally work as expected, waiting for the process to exit before proceeding. However, there are situations where it may not behave as intended due to process behavior or certain configurations. Below are possible issues and suggestions for resolving them:Common Issues and Fixes
Notepad Spawns a Separate Process
Some applications, like
notepad.exe, may spawn child processes and exit themselves, causingWaitForExitto return prematurely. This could be the reason whyWaitForExitis not behaving as expected.Process.EnableRaisingEventsto track the process exit via an event handler:Process Termination Timeout
If the process does not exit within the specified timeout (e.g.,
5000ms), it will return control back to your code without waiting further.p.HasExited.Detached Process
If the process detaches itself from the parent process,
WaitForExitwill not work.Missing Privileges or Permission Issues
If the process does not have sufficient privileges, it may not execute properly, leading to unexpected behavior.
Adjusted Code Example
Here's an improved version of your code with better handling:
Debugging Tips
notepad.exe.Let me know if you need further clarification!
Jaish MathewsPosted Dec 27, 2024, 4:49 PM
Not a problem at all—what matters most is whether this suggestion proves helpful to you
Pat HanksPosted Dec 27, 2024, 3:01 PM
Sorry for the delay in responding I didn't get a notification of your answer. I did switch from Notepad to the actual program I intended to use and it worked. I;m glad you exposed the EnableRaisingEvents propertiy as I wasn;t aware of it.