简体   繁体   中英

How to start processes sequentially through code

I have to run 3 processes sequentially, one after other. The second process must start after first process' completion. I work in C#. I have used Process.Start() method, Where it kicks on all at same time. Can anyone help me.

One way of doing it adding a handler for the Exited event of the first process, and then starting the second process from there.

void StartProcessOne() {
    Process p = Process.Start("foo", "bar");
    p.Exited += (sender, e) => StartProcessTwo();
    p.Start();
}

void StartProcessTwo() {
    Process p = Process.Start("foo2", "bar2");
    p.Exited += (sender, e) => StartProcessThree();
    p.Start();
}

...

You can also use the WaitForExit() method, which waits for the process to end before continuing execution of your code. Note, however, this makes your own process stop execution until the other process terminates. This can leave you with an unresponsive user interface and such, which can be quite undesirable. ( source )

Process.Start("yourprogram.exe").WaitForExit();
Process.Start("yournextprogram.exe").WaitForExit();

and so on...

You can accomplish this by responding to the Process.Exited event.
You should use this approach instead of WaitForExit() because the latter will block your program from responding to user input, etc...

private int n = 0;

private void StartAProcess()
{
    Process process = new Process {
        StartInfo = {FileName = "cmd.exe", Arguments = "pause"}, 
        EnableRaisingEvents = true};
    process.Exited += process_Exited;
    process.Start();
    n++;
}

void process_Exited(object sender, EventArgs e)
{
    if (n < 3) StartAProcess();
}

try this code for each process

Process.WaitForExit()

http://msdn.microsoft.com/en-us/library/aa326953(v=VS.71).aspx

If you are using .NET 4 you could use the System.Threading.Tasks API. If your graph gets more complex you may get some mileage from http://pdag.codeplex.com (I must confess, this is my work).

You need to do a process.join() to wait for the first process to complete before submitting the next one. However, the bigger question is why you are using Process.Start() - for asynchronous tasks - when you actually want them to run synchronously? Just calling:

a();
b();
c();

will run them one after another.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM