简体   繁体   中英

How to write Process.Start and get the ExitCode in one line?

Many examples and MSDN are using a new Process to get the exitcode, however, creat a new variable looks not so grace.So, I tried this

Process.Start("Application.exe", "parameter").WaitForExit().ExitCode

aimed to get the exitcode in one line but failed. And is there any solution of this writing?

It doesn't work like that because WaitForExit() returns a bool , which doesn't have an ExitCode property. If you want this behavior on one line, you'll have to implement it yourself in a method and call it.

public int RunAndGetCode(string executable, string parameter) 
{
    var process = Process.Start(executable, parameter).WaitForExit();
    return process.ExitCode; 
} 

// then later 
var code = RunAndGetCode("Application.exe", "parameter"); 

So... That's not quite how Process works. You could write a wrapper class that allows you to do it in one one line, or using a using block, but when you have to wait for any process, that means you're locking up your own process while waiting for it. In Windows that is terrible practice. The way it's designed in C#, it allows your own process to do other work while the process you called has returned. (Wrote this on mobile device; apologies for errors)

So, in short, no, but I see nothing wrong with this:

Process p = new Process();
P.Start();

While(!p.WaitForExit()) {
    //do work while you wait for the calling process to return
}

var exitCode = p.ExitCode

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