Michael
Michael

Reputation: 121

C# - Telling Process.Start to wait until previous instance has finished

I am currently calling a process which inports parameters from a text file,

Although when one line of the text file is read it works correctly, but the second line of the text file is executed straight after. Is there any way to tell Process.Start to wait until the previous command has finished?

static void Main(string[] args)
{
    foreach (string exename in System.IO.File.ReadAllLines("test.txt"))
    {
        Process.Start("test.exe", "\"" + exename + "\"");
    }

}

Upvotes: 1

Views: 1657

Answers (3)

IAmTimCorey
IAmTimCorey

Reputation: 16757

I believe you need to add a .WaitForExit() command at the end of your statement like so:

Process.Start("test.exe", "\"" + exename + "\"").WaitForExit();

However, this will be an infinite wait (usually a bad thing). If you want to add a timeout, you can use the overload of the method like so:

Process.Start("test.exe", "\"" + exename + "\"").WaitForExit(30000);

The 30,000 represents 30 seconds (the int is milliseconds).

Upvotes: 1

jgauffin
jgauffin

Reputation: 101140

static void Main(string[] args)
{
    foreach (string exename in System.IO.File.ReadAllLines("test.txt"))
    {
        Process.Start("test.exe", "\"" + exename + "\"").WaitForExit();
    }

}

Documented at MSDN. I usually google "MSDN [class/method/property]". In this case you could have googled "msdn process class" and you would have found the method.

Upvotes: 5

Ta01
Ta01

Reputation: 31610

You could see if the process you just launched was found via GetProcesses, if not try again after a fixed interval before you launch the second process

Upvotes: 0

Related Questions