繁体   English   中英

Process.Start vs Process`p = C#中的新进程()`

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

正如本文所述 ,有两种方法可以在C#中调用另一个进程。

Process.Start("hello");

Process p = new Process();
p.StartInfo.FileName = "hello.exe";
p.Start();
p.WaitForExit();
  • Q1:每种方法的优缺点是什么?
  • Q2:如何检查Process.Start()方法是否发生错误?

对于简单的情况,优点主要是方便。 显然,你有更多选项(工作路径,在shell-exec之间选择等)和ProcessStartInfo路由,但是还有一个Process.Start(ProcessStartInfo)静态方法。

重新检查错误; Process.Start返回Process对象,因此您可以等待退出并在需要时检查错误代码。 如果要捕获stderr,可能需要使用ProcessStartInfo方法。

使用第一种方法,您可能无法使用WaitForExit ,因为如果进程已在运行,则该方法返回null。

如何检查新进程是否已启动,方法之间存在差异。 第一个返回Process对象或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
}

第二个返回一个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();

差别很小。 静态方法返回一个进程对象,因此您仍然可以使用“p.WaitForExit()”等 - 使用创建新进程的方法,在启动之前更容易修改进程参数(处理器关联性等)处理。

除此之外 - 没有区别。 两种方式都创建了一个新的流程对象。

在你的第二个例子中 - 这与此相同:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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