C# 中的 Process.Start 与 Process `p = new Process()` ?
正如这篇文章中所要求的,有两种方法可以在 C# 中调用另一个进程。
Process.Start("hello");
Q1
Process p = new Process();
p.StartInfo.FileName = "hello.exe";
p.Start();
p.WaitForExit();
- :每种方法的优点/缺点是什么?
- Q2 : 如何检查
Process.Start()
方法是否发生错误?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
对于第一种方法,您可能无法使用
WaitForExit
,因为如果进程已在运行,该方法将返回 null。检查新进程是否已启动的方式因方法而异。第一个返回
Process
对象或null
:第二个返回
bool
: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 ornull
:The second one returns a
bool
:对于简单的情况,优点主要是方便。显然,使用 ProcessStartInfo 路由您有更多选项(工作路径、在 shell-exec 之间进行选择等),但还有一个 Process.Start(ProcessStartInfo) 静态方法。
重新检查错误; Process.Start 返回 Process 对象,因此您可以等待退出并根据需要检查错误代码。如果您想捕获 stderr,您可能需要任一 ProcessStartInfo 方法。
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.
差别很小。静态方法返回一个进程对象,因此您仍然可以使用“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: