如 this post 中所述,在 C# 中有两种调用另一个进程的方法。
Process.Start("hello");
和
Process p = new Process();
p.StartInfo.FileName = "hello.exe";
p.Start();
p.WaitForExit();
- 问题 1:每种方法的优缺点是什么?
- Q2:如何检查
Process.Start()
方法是否出错?
最佳答案
对于第一种方法,您可能无法使用 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();
关于c# - Process.Start 与 C# 中的 Process `p = new Process()`?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4977548/