简体   繁体   English

如何编写 Process.Start 并在一行中获取 ExitCode?

[英]How to write Process.Start and get the ExitCode in one line?

Many examples and MSDN are using a new Process to get the exitcode, however, creat a new variable looks not so grace.So, I tried this许多示例和 MSDN 都使用新的Process来获取退出代码,但是,创建一个新变量看起来不那么优雅。所以,我尝试了这个

Process.Start("Application.exe", "parameter").WaitForExit().ExitCode

aimed to get the exitcode in one line but failed.旨在在一行中获取退出代码但失败了。 And is there any solution of this writing?这篇文章有什么解决方案吗?

It doesn't work like that because WaitForExit() returns a bool , which doesn't have an ExitCode property.它不会像那样工作,因为WaitForExit()返回一个没有ExitCode属性的bool If you want this behavior on one line, you'll have to implement it yourself in a method and call it.如果您希望在一行中执行此行为,则必须自己在一个方法中实现它并调用它。

public int RunAndGetCode(string executable, string parameter) 
{
    var process = Process.Start(executable, parameter).WaitForExit();
    return process.ExitCode; 
} 

// then later 
var code = RunAndGetCode("Application.exe", "parameter"); 

So... That's not quite how Process works.所以...这不是 Process 的工作原理。 You could write a wrapper class that allows you to do it in one one line, or using a using block, but when you have to wait for any process, that means you're locking up your own process while waiting for it.您可以编写一个包装类,允许您在一行中完成它,或者使用 using 块,但是当您必须等待任何进程时,这意味着您在等待它时锁定了自己的进程。 In Windows that is terrible practice.在 Windows 中,这是可怕的做法。 The way it's designed in C#, it allows your own process to do other work while the process you called has returned.它在 C# 中的设计方式允许您自己的进程在您调用的进程返回时执行其他工作。 (Wrote this on mobile device; apologies for errors) (在移动设备上写的;为错误道歉)

So, in short, no, but I see nothing wrong with this:所以,简而言之,不,但我认为这没有任何问题:

Process p = new Process();
P.Start();

While(!p.WaitForExit()) {
    //do work while you wait for the calling process to return
}

var exitCode = p.ExitCode

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM