C# - Making a Process.Start Wait Until the Process Has Start-Up

How can I start a new Process and wait until it finishes?

After you call Start() add: Process.WaitForExit()

 var myProcess = new Process {StartInfo = new ProcessStartInfo(processPath)};
myProcess.Start().WaitForExit();

Wait until a process ends

I think you just want this:

var process = Process.Start(...);
process.WaitForExit();

See the MSDN page for the method. It also has an overload where you can specify the timeout, so you're not potentially waiting forever.

Wait for process start

The Ugly Way

Generally, when waiting for a process to finish loading, you would call

Process.WaitForInputIdle()

From MSDN :

Causes the Process component to wait indefinitely for the associated process to enter an idle state. This overload applies only to processes with a user interface and, therefore, a message loop.

With explorer.exe this will most likely not work, as this process often spawns a child process and instantly dies.

The workaround would be to launch the process, Sleep for say, 250-500ms, then find the new Process using some godawful hack, and then call WaitForInputIdle on that Process.

An Alternative

If you are willing to start explorer.exe minimized, you could do it like this:

ProcessStartInfo psi = new ProcessStartInfo();
psi.FileName = "explorer.exe";
psi.Arguments = "/separate";
psi.UseShellExecute = true;
psi.WindowStyle = ProcessWindowStyle.Minimized;
Process.Start(psi);

Delay process start until parent process close

There are 2 actual ways to do this.

First, you can use OS level synchronization objects like Mutex. In your first app create new named Mutex and release it before app closed. In second app wait Mutex released by WaitOne.

First process should create new mutex and block other processes:

Mutex mtx = new Mutex(true, "SomeName");
// start second process
mtx.ReleaseMutex();

Second process:

Mutex mtx = new Mutex(false, "SomeName");

// next line will block current thread until mutex will be released
mtx.WaitOne();

// your logic here

Also you can check running processes in your second app and wait when first app will closed:

while(Process.GetProcessesByName("YourFirstProcessName").Any())
{
Thread.Sleep(1000);
}

Keep in mind that both solutions involve overhead because Mutex is an operating system level synchronization object and Process.GetProcessesByName also calls external API.

C# Process.Start - how to enforce WaitForExit

Ok, after bashing my head against a wall for the best part of a day, I found this... Start an offline ClickOnce Application and wait for Exit

Used the mutex option. Fek me Microsoft, you've take something that used to be really simple and made a real horse's ass out of it.

I was just about to scrap my called exe's and create one monster - was feeling ill at the thought.



Related Topics



Leave a reply



Submit