【问题标题】:Process.Start vs Process `p = new Process()` in C#?C# 中的 Process.Start 与 Process `p = new Process()`?
【发布时间】:2011-02-12 10:27:47
【问题描述】:

正如this post 中所问的那样,在 C# 中调用另一个进程有两种方法。

Process.Start("hello");

和

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

【问题讨论】:

    标签: c# process interprocess


    【解决方案1】:

    对于第一种方法,您可能无法使用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();
    

    【讨论】:

      【解决方案2】:

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

      重新检查错误; Process.Start 返回 Process 对象,因此您可以等待退出并根据需要检查错误代码。如果你想捕获标准错误,你可能需要 ProcessStartInfo 方法中的任何一种。

      【讨论】:

      • 你能给我举个例子吗?如果必须获取对象并等待退出,在我看来,由于简单,没有理由使用 Process.start()。
      • @prosseek 好的;假设您想要捕获 stdout 和 stderr,在另一个用户的帐户中运行它,并在它完成时获取一个事件。但是,是的;对于简单的情况,静态方法更容易。
      【解决方案3】:

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

      除此之外 - 没有区别。双向创建一个新的进程对象。

      在您的第二个示例中 - 与此相同:

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2014-03-18
        • 2012-03-26
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-12-17
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多