gpt4 book ai didi

c# - Process.Start 与 C# 中的 Process `p = new Process()`?

转载 作者:行者123 更新时间:2023-11-30 13:24:21 26 4
gpt4 key购买 nike

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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com