简体   繁体   中英

Process.Start vs Process `p = new Process()` in C#?

As is asked in this post , there are two ways to call another process in C#.

Process.Start("hello");

And

Process p = new Process();
p.StartInfo.FileName = "hello.exe";
p.Start();
p.WaitForExit();
  • Q1 : What are the pros/cons of each approach?
  • Q2 : How to check if error happens with the Process.Start() method?

For simple cases, the advantage is mainly convenience. Obviously you have more options (working path, choosing between shell-exec, etc) with the ProcessStartInfo route, but there is also a Process.Start(ProcessStartInfo) static method.

Re checking for errors; Process.Start returns the Process object, so you can wait for exit and check the error code if you need. If you want to capture stderr, you probably want either of the ProcessStartInfo approaches.

With the first method you might not be able to use WaitForExit , as the method returns null if the process is already running.

How you check if a new process was started differs between the methods. The first one returns a Process object or null :

Process p = Process.Start("hello");
if (p != null) {
  // A new process was started
  // Here it's possible to wait for it to end:
  p.WaitForExit();
} else {
  // The process was already running
}

The second one returns a bool :

Process p = new Process();
p.StartInfo.FileName = "hello.exe";
bool s = p.Start();
if (s) {
  // A new process was started
} else {
  // The process was already running
}
p.WaitForExit();

Very little difference. The static method returns a process object, so you can still use the "p.WaitForExit()" etc - using the method where you create a new process it would be easier to modify the process parameters (processor affinity and such) before launching the process.

Other than that - no difference. A new process object is created both ways.

In your second example - that is identical to this:

Process p = Process.Start("hello.exe");
p.WaitForExit();

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