正如这篇文章中所问的,有两种方法可以在 C# 中调用另一个进程。
Process.Start("hello");
和
Process p = new Process();
p.StartInfo.FileName = "hello.exe";
p.Start();
p.WaitForExit();
- Q1:每种方法的优缺点是什么?
- Q2 : 如何检查
Process.Start()
方法是否发生错误?
正如这篇文章中所问的,有两种方法可以在 C# 中调用另一个进程。
Process.Start("hello");
和
Process p = new Process();
p.StartInfo.FileName = "hello.exe";
p.Start();
p.WaitForExit();
Process.Start()
方法是否发生错误?对于简单的情况,优点主要是方便。显然,使用 ProcessStartInfo 路由您有更多选项(工作路径、在 shell-exec 之间进行选择等),但还有一个 Process.Start(ProcessStartInfo) 静态方法。
重新检查错误;Process.Start 返回 Process 对象,因此您可以等待退出并根据需要检查错误代码。如果您想捕获标准错误,您可能需要任何一种 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();