ProcessStartInfo挂在“WaitForExit”上?为什么?

时间:2008-09-26 13:46:56

标签: c# processstartinfo

我有以下代码:

info = new System.Diagnostics.ProcessStartInfo("TheProgram.exe", String.Join(" ", args));
info.CreateNoWindow = true;
info.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden;
info.RedirectStandardOutput = true;
info.UseShellExecute = false;
System.Diagnostics.Process p = System.Diagnostics.Process.Start(info);
p.WaitForExit();
Console.WriteLine(p.StandardOutput.ReadToEnd()); //need the StandardOutput contents

我知道我正在启动的进程的输出大约是7MB。在Windows控制台中运行它可以正常工作。不幸的是,这会在WaitForExit上无限期挂起。另请注意,对于较小的输出(例如3KB),此代码不会挂起。

ProcessStartInfo中的内部StandardOutput是否有可能无法缓冲7MB?如果是这样,我该怎么做呢?如果没有,我做错了什么?

22 个答案:

答案 0 :(得分:355)

问题在于,如果重定向StandardOutput和/或StandardError,内部缓冲区可能会变满。无论您使用哪种订单,都可能存在问题:

  • 如果您在阅读StandardOutput之前等待进程退出,则进程可能会阻止尝试写入进程,因此进程永远不会结束。
  • 如果您使用ReadToEnd从StandardOutput读取,那么您的进程可能会阻止进程永远不会关闭StandardOutput(例如,如果它永远不会终止,或者它被阻止写入到StandardError)。

解决方案是使用异步读取来确保缓冲区不会满。为了避免任何死锁并收集StandardOutputStandardError的所有输出,您可以这样做:

编辑:如果发生超时,请参阅下面的答案,了解如何避免 ObjectDisposedException

using (Process process = new Process())
{
    process.StartInfo.FileName = filename;
    process.StartInfo.Arguments = arguments;
    process.StartInfo.UseShellExecute = false;
    process.StartInfo.RedirectStandardOutput = true;
    process.StartInfo.RedirectStandardError = true;

    StringBuilder output = new StringBuilder();
    StringBuilder error = new StringBuilder();

    using (AutoResetEvent outputWaitHandle = new AutoResetEvent(false))
    using (AutoResetEvent errorWaitHandle = new AutoResetEvent(false))
    {
        process.OutputDataReceived += (sender, e) => {
            if (e.Data == null)
            {
                outputWaitHandle.Set();
            }
            else
            {
                output.AppendLine(e.Data);
            }
        };
        process.ErrorDataReceived += (sender, e) =>
        {
            if (e.Data == null)
            {
                errorWaitHandle.Set();
            }
            else
            {
                error.AppendLine(e.Data);
            }
        };

        process.Start();

        process.BeginOutputReadLine();
        process.BeginErrorReadLine();

        if (process.WaitForExit(timeout) &&
            outputWaitHandle.WaitOne(timeout) &&
            errorWaitHandle.WaitOne(timeout))
        {
            // Process completed. Check process.ExitCode here.
        }
        else
        {
            // Timed out.
        }
    }
}

答案 1 :(得分:90)

Process.StandardOutput的{​​{3}}表示在您等待之前阅读,否则您可能会死锁,下面复制了代码段:

 // Start the child process.
 Process p = new Process();
 // Redirect the output stream of the child process.
 p.StartInfo.UseShellExecute = false;
 p.StartInfo.RedirectStandardOutput = true;
 p.StartInfo.FileName = "Write500Lines.exe";
 p.Start();
 // Do not wait for the child process to exit before
 // reading to the end of its redirected stream.
 // p.WaitForExit();
 // Read the output stream first and then wait.
 string output = p.StandardOutput.ReadToEnd();
 p.WaitForExit();

答案 2 :(得分:18)

Mark Byers的回答非常好,但我只想添加以下内容:在outputWaitHandle和errorWaitHandle被释放之前,需要删除OutputDataReceived和ErrorDataReceived委托。如果进程在超出超时后继续输出数据然后终止,则在处理后将访问outputWaitHandle和errorWaitHandle变量。

(仅供参考我不得不加上这个警告作为答案,因为我无法评论他的帖子。)

答案 3 :(得分:16)

当进程超时时,会发生未处理的ObjectDisposedException问题。在这种情况下,条件的其他部分:

if (process.WaitForExit(timeout) 
    && outputWaitHandle.WaitOne(timeout) 
    && errorWaitHandle.WaitOne(timeout))

未执行。我通过以下方式解决了这个问题:

using (AutoResetEvent outputWaitHandle = new AutoResetEvent(false))
using (AutoResetEvent errorWaitHandle = new AutoResetEvent(false))
{
    using (Process process = new Process())
    {
        // preparing ProcessStartInfo

        try
        {
            process.OutputDataReceived += (sender, e) =>
                {
                    if (e.Data == null)
                    {
                        outputWaitHandle.Set();
                    }
                    else
                    {
                        outputBuilder.AppendLine(e.Data);
                    }
                };
            process.ErrorDataReceived += (sender, e) =>
                {
                    if (e.Data == null)
                    {
                        errorWaitHandle.Set();
                    }
                    else
                    {
                        errorBuilder.AppendLine(e.Data);
                    }
                };

            process.Start();

            process.BeginOutputReadLine();
            process.BeginErrorReadLine();

            if (process.WaitForExit(timeout))
            {
                exitCode = process.ExitCode;
            }
            else
            {
                // timed out
            }

            output = outputBuilder.ToString();
        }
        finally
        {
            outputWaitHandle.WaitOne(timeout);
            errorWaitHandle.WaitOne(timeout);
        }
    }
}

答案 4 :(得分:14)

这是一个更现代的,基于任务并行库(TPL)的.NET 4.5及更高版本的解决方案。

用法示例

try
{
    var exitCode = await StartProcess(
        "dotnet", 
        "--version", 
        @"C:\",
        10000, 
        Console.Out, 
        Console.Out);
    Console.WriteLine($"Process Exited with Exit Code {exitCode}!");
}
catch (TaskCanceledException)
{
    Console.WriteLine("Process Timed Out!");
}

实施

public static async Task<int> StartProcess(
    string filename,
    string arguments,
    string workingDirectory= null,
    int? timeout = null,
    TextWriter outputTextWriter = null,
    TextWriter errorTextWriter = null)
{
    using (var process = new Process()
    {
        StartInfo = new ProcessStartInfo()
        {
            CreateNoWindow = true,
            Arguments = arguments,
            FileName = filename,
            RedirectStandardOutput = outputTextWriter != null,
            RedirectStandardError = errorTextWriter != null,
            UseShellExecute = false,
            WorkingDirectory = workingDirectory
        }
    })
    {
        process.Start();
        var cancellationTokenSource = timeout.HasValue ?
            new CancellationTokenSource(timeout.Value) :
            new CancellationTokenSource();

        var tasks = new List<Task>(3) { process.WaitForExitAsync(cancellationTokenSource.Token) };
        if (outputTextWriter != null)
        {
            tasks.Add(ReadAsync(
                x =>
                {
                    process.OutputDataReceived += x;
                    process.BeginOutputReadLine();
                },
                x => process.OutputDataReceived -= x,
                outputTextWriter,
                cancellationTokenSource.Token));
        }

        if (errorTextWriter != null)
        {
            tasks.Add(ReadAsync(
                x =>
                {
                    process.ErrorDataReceived += x;
                    process.BeginErrorReadLine();
                },
                x => process.ErrorDataReceived -= x,
                errorTextWriter,
                cancellationTokenSource.Token));
        }

        await Task.WhenAll(tasks);
        return process.ExitCode;
    }
}

/// <summary>
/// Waits asynchronously for the process to exit.
/// </summary>
/// <param name="process">The process to wait for cancellation.</param>
/// <param name="cancellationToken">A cancellation token. If invoked, the task will return
/// immediately as cancelled.</param>
/// <returns>A Task representing waiting for the process to end.</returns>
public static Task WaitForExitAsync(
    this Process process,
    CancellationToken cancellationToken = default(CancellationToken))
{
    process.EnableRaisingEvents = true;

    var taskCompletionSource = new TaskCompletionSource<object>();

    EventHandler handler = null;
    handler = (sender, args) =>
    {
        process.Exited -= handler;
        taskCompletionSource.TrySetResult(null);
    };
    process.Exited += handler;

    if (cancellationToken != default(CancellationToken))
    {
        cancellationToken.Register(
            () =>
            {
                process.Exited -= handler;
                taskCompletionSource.TrySetCanceled();
            });
    }

    return taskCompletionSource.Task;
}

/// <summary>
/// Reads the data from the specified data recieved event and writes it to the
/// <paramref name="textWriter"/>.
/// </summary>
/// <param name="addHandler">Adds the event handler.</param>
/// <param name="removeHandler">Removes the event handler.</param>
/// <param name="textWriter">The text writer.</param>
/// <param name="cancellationToken">The cancellation token.</param>
/// <returns>A task representing the asynchronous operation.</returns>
public static Task ReadAsync(
    this Action<DataReceivedEventHandler> addHandler,
    Action<DataReceivedEventHandler> removeHandler,
    TextWriter textWriter,
    CancellationToken cancellationToken = default(CancellationToken))
{
    var taskCompletionSource = new TaskCompletionSource<object>();

    DataReceivedEventHandler handler = null;
    handler = new DataReceivedEventHandler(
        (sender, e) =>
        {
            if (e.Data == null)
            {
                removeHandler(handler);
                taskCompletionSource.TrySetResult(null);
            }
            else
            {
                textWriter.WriteLine(e.Data);
            }
        });

    addHandler(handler);

    if (cancellationToken != default(CancellationToken))
    {
        cancellationToken.Register(
            () =>
            {
                removeHandler(handler);
                taskCompletionSource.TrySetCanceled();
            });
    }

    return taskCompletionSource.Task;
}

答案 5 :(得分:7)

罗布回答说,又为我节省了几个小时的试验。在等待之前读取输出/错误缓冲区:

// Read the output stream first and then wait.
string output = p.StandardOutput.ReadToEnd();
p.WaitForExit();

答案 6 :(得分:6)

我们也有这个问题(或变体)。

尝试以下方法:

1)向p.WaitForExit(nnnn)添加超时;其中nnnn以毫秒为单位。

2)在WaitForExit调用之前放入ReadToEnd调用。这个 我们看到MS推荐的内容。

答案 7 :(得分:4)

EM0

https://stackoverflow.com/a/17600012/4151626

由于内部超时以及衍生应用程序使用StandardOutput和StandardError,其他解决方案(包括EM0)仍然因我的应用程序而死锁。这对我有用:

Process p = new Process()
{
  StartInfo = new ProcessStartInfo()
  {
    FileName = exe,
    Arguments = args,
    UseShellExecute = false,
    RedirectStandardOutput = true,
    RedirectStandardError = true
  }
};
p.Start();

string cv_error = null;
Thread et = new Thread(() => { cv_error = p.StandardError.ReadToEnd(); });
et.Start();

string cv_out = null;
Thread ot = new Thread(() => { cv_out = p.StandardOutput.ReadToEnd(); });
ot.Start();

p.WaitForExit();
ot.Join();
et.Join();

编辑:将StartInfo初始化添加到代码示例

答案 8 :(得分:2)

我这样解决了:

            Process proc = new Process();
            proc.StartInfo.FileName = batchFile;
            proc.StartInfo.UseShellExecute = false;
            proc.StartInfo.CreateNoWindow = true;
            proc.StartInfo.RedirectStandardError = true;
            proc.StartInfo.RedirectStandardInput = true;
            proc.StartInfo.RedirectStandardOutput = true;
            proc.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;      
            proc.Start();
            StreamWriter streamWriter = proc.StandardInput;
            StreamReader outputReader = proc.StandardOutput;
            StreamReader errorReader = proc.StandardError;
            while (!outputReader.EndOfStream)
            {
                string text = outputReader.ReadLine();                    
                streamWriter.WriteLine(text);
            }

            while (!errorReader.EndOfStream)
            {                   
                string text = errorReader.ReadLine();
                streamWriter.WriteLine(text);
            }

            streamWriter.Close();
            proc.WaitForExit();

我重定向了输入,输出和错误,并处理了输出和错误流的读取。 此解决方案适用于适用于Windows 7和Windows 8的SDK 7-8 8.1

答案 9 :(得分:1)

我尝试通过考虑Mark Byers,Rob,stevejay的答案来创建一个使用异步流读取来解决问题的类。这样做我意识到存在与异步进程输出流读取相关的错误。

我在微软报告了这个错误:https://connect.microsoft.com/VisualStudio/feedback/details/3119134

要点:

  

你做不到:

     

process.BeginOutputReadLine();的Process.Start();

     

您将收到System.InvalidOperationException:StandardOut具有   未被重定向或过程尚未开始。

     

=============================================== ================================================== ===========================

     

然后你必须在进程之后启动异步输出读取   开始:

     

的Process.Start(); process.BeginOutputReadLine();

     

这样做,因为输出流可以接收竞争条件   将数据设置为异步之前的数据:

process.Start(); 
// Here the operating system could give the cpu to another thread.  
// For example, the newly created thread (Process) and it could start writing to the output
// immediately before next line would execute. 
// That create a race condition.
process.BeginOutputReadLine();
  

=============================================== ================================================== ===========================

     

然后有些人可能会说你只需阅读流   在将其设置为异步之前。但同样的问题发生了。那里   将是同步读取和设置之间的竞争条件   流进入异步模式。

     

=============================================== ================================================== ===========================

     

无法实现输出流的安全异步读取   “Process”和“ProcessStartInfo”的实际方式中的进程   已经设计好了。

您可能更喜欢使用其他用户建议的异步读取。但是你应该知道,由于竞争条件你可能会错过一些信息。

答案 10 :(得分:1)

我最终用来避免所有复杂性的解决方法:

var outputFile = Path.GetTempFileName();
info = new System.Diagnostics.ProcessStartInfo("TheProgram.exe", String.Join(" ", args) + " > " + outputFile + " 2>&1");
info.CreateNoWindow = true;
info.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden;
info.UseShellExecute = false;
System.Diagnostics.Process p = System.Diagnostics.Process.Start(info);
p.WaitForExit();
Console.WriteLine(File.ReadAllText(outputFile)); //need the StandardOutput contents

因此,我创建了一个临时文件,使用> outputfile > 2>&1将输出和错误均重定向到该文件,然后在该过程完成后才读取该文件。

对于要对输出执行其他操作的方案,其他解决方案也很好,但是对于简单的操作,这可以避免很多复杂性。

答案 11 :(得分:1)

在阅读完所有帖子后,我决定采用MarkoAvlijaš的综合解决方案。 然而,它并没有解决我的所有问题。

在我们的环境中,我们有一个Windows服务,计划运行数百个不同的.bat .cmd .exe,...等文件,这些文件多年来积累并由不同的人和不同风格编写。我们无法控制程序的编写和脚本,我们负责安排,运行和报告成功/失败。

所以我在这里尝试了几乎所有的建议,并取得了不同程度的成功。 Marko的答案几乎是完美的,但是当作为服务运行时,它并不总是捕获标准输出。我从来没有深究其中的原因。

我们发现在我们所有情况下都能使用的唯一解决方案是:http://csharptest.net/319/using-the-processrunner-class/index.html

答案 12 :(得分:1)

我知道这已经过时了,但在阅读完这一页之后,没有一个解决方案对我有用,虽然我没有尝试过Muhammad Rehan因为代码有点难以理解,尽管我猜他还在正确的轨道。当我说它不起作用并不完全正确时,有时它会正常工作,我想这与EOF标记之前的输出长度有关。

无论如何,对我有用的解决方案是使用不同的线程来读取StandardOutput和StandardError并编写消息。

        StreamWriter sw = null;
        var queue = new ConcurrentQueue<string>();

        var flushTask = new System.Timers.Timer(50);
        flushTask.Elapsed += (s, e) =>
        {
            while (!queue.IsEmpty)
            {
                string line = null;
                if (queue.TryDequeue(out line))
                    sw.WriteLine(line);
            }
            sw.FlushAsync();
        };
        flushTask.Start();

        using (var process = new Process())
        {
            try
            {
                process.StartInfo.FileName = @"...";
                process.StartInfo.Arguments = $"...";
                process.StartInfo.UseShellExecute = false;
                process.StartInfo.RedirectStandardOutput = true;
                process.StartInfo.RedirectStandardError = true;

                process.Start();

                var outputRead = Task.Run(() =>
                {
                    while (!process.StandardOutput.EndOfStream)
                    {
                        queue.Enqueue(process.StandardOutput.ReadLine());
                    }
                });

                var errorRead = Task.Run(() =>
                {
                    while (!process.StandardError.EndOfStream)
                    {
                        queue.Enqueue(process.StandardError.ReadLine());
                    }
                });

                var timeout = new TimeSpan(hours: 0, minutes: 10, seconds: 0);

                if (Task.WaitAll(new[] { outputRead, errorRead }, timeout) &&
                    process.WaitForExit((int)timeout.TotalMilliseconds))
                {
                    if (process.ExitCode != 0)
                    {
                        throw new Exception($"Failed run... blah blah");
                    }
                }
                else
                {
                    throw new Exception($"process timed out after waiting {timeout}");
                }
            }
            catch (Exception e)
            {
                throw new Exception($"Failed to succesfully run the process.....", e);
            }
        }
    }

希望这有助于某些人认为这可能会如此艰难!

答案 13 :(得分:1)

简介

当前接受的答案不起作用(抛出异常)并且有太多的变通方法但没有完整的代码。这显然是在浪费很多人的时间,因为这是一个很受欢迎的问题。

结合Mark Byers的回答和Karol Tyl的回答我根据我想要如何使用Process.Start方法编写了完整的代码。

用法

我用它来创建围绕git命令的进度对话框。这就是我使用它的方式:

    private bool Run(string fullCommand)
    {
        Error = "";
        int timeout = 5000;

        var result = ProcessNoBS.Start(
            filename: @"C:\Program Files\Git\cmd\git.exe",
            arguments: fullCommand,
            timeoutInMs: timeout,
            workingDir: @"C:\test");

        if (result.hasTimedOut)
        {
            Error = String.Format("Timeout ({0} sec)", timeout/1000);
            return false;
        }

        if (result.ExitCode != 0)
        {
            Error = (String.IsNullOrWhiteSpace(result.stderr)) 
                ? result.stdout : result.stderr;
            return false;
        }

        return true;
    }

理论上你也可以组合stdout和stderr,但我还没有测试过。

代码

public struct ProcessResult
{
    public string stdout;
    public string stderr;
    public bool hasTimedOut;
    private int? exitCode;

    public ProcessResult(bool hasTimedOut = true)
    {
        this.hasTimedOut = hasTimedOut;
        stdout = null;
        stderr = null;
        exitCode = null;
    }

    public int ExitCode
    {
        get 
        {
            if (hasTimedOut)
                throw new InvalidOperationException(
                    "There was no exit code - process has timed out.");

            return (int)exitCode;
        }
        set
        {
            exitCode = value;
        }
    }
}

public class ProcessNoBS
{
    public static ProcessResult Start(string filename, string arguments,
        string workingDir = null, int timeoutInMs = 5000,
        bool combineStdoutAndStderr = false)
    {
        using (AutoResetEvent outputWaitHandle = new AutoResetEvent(false))
        using (AutoResetEvent errorWaitHandle = new AutoResetEvent(false))
        {
            using (var process = new Process())
            {
                var info = new ProcessStartInfo();

                info.CreateNoWindow = true;
                info.FileName = filename;
                info.Arguments = arguments;
                info.UseShellExecute = false;
                info.RedirectStandardOutput = true;
                info.RedirectStandardError = true;

                if (workingDir != null)
                    info.WorkingDirectory = workingDir;

                process.StartInfo = info;

                StringBuilder stdout = new StringBuilder();
                StringBuilder stderr = combineStdoutAndStderr
                    ? stdout : new StringBuilder();

                var result = new ProcessResult();

                try
                {
                    process.OutputDataReceived += (sender, e) =>
                    {
                        if (e.Data == null)
                            outputWaitHandle.Set();
                        else
                            stdout.AppendLine(e.Data);
                    };
                    process.ErrorDataReceived += (sender, e) =>
                    {
                        if (e.Data == null)
                            errorWaitHandle.Set();
                        else
                            stderr.AppendLine(e.Data);
                    };

                    process.Start();

                    process.BeginOutputReadLine();
                    process.BeginErrorReadLine();

                    if (process.WaitForExit(timeoutInMs))
                        result.ExitCode = process.ExitCode;
                    // else process has timed out 
                    // but that's already default ProcessResult

                    result.stdout = stdout.ToString();
                    if (combineStdoutAndStderr)
                        result.stderr = null;
                    else
                        result.stderr = stderr.ToString();

                    return result;
                }
                finally
                {
                    outputWaitHandle.WaitOne(timeoutInMs);
                    errorWaitHandle.WaitOne(timeoutInMs);
                }
            }
        }
    }
}

答案 14 :(得分:1)

上述答案都没有完成。

Rob解决方案挂起,而Mark Byers&#39;解决方案获得处理的异常。(我尝试了其他答案的&#34;解决方案&#34;。

所以我决定提出另一个解决方案:

public void GetProcessOutputWithTimeout(Process process, int timeoutSec, CancellationToken token, out string output, out int exitCode)
{
    string outputLocal = "";  int localExitCode = -1;
    var task = System.Threading.Tasks.Task.Factory.StartNew(() =>
    {
        outputLocal = process.StandardOutput.ReadToEnd();
        process.WaitForExit();
        localExitCode = process.ExitCode;
    }, token);

    if (task.Wait(timeoutSec, token))
    {
        output = outputLocal;
        exitCode = localExitCode;
    }
    else
    {
        exitCode = -1;
        output = "";
    }
}

using (var process = new Process())
{
    process.StartInfo = ...;
    process.Start();
    string outputUnicode; int exitCode;
    GetProcessOutputWithTimeout(process, PROCESS_TIMEOUT, out outputUnicode, out exitCode);
}

此代码经过调试并完美运行。

答案 15 :(得分:1)

这篇文章可能已经过时,但我发现它通常挂起的主要原因是由于redirectStandardoutput的堆栈溢出或者你有redirectStandarderror。

由于输出数据或错误数据很大,它将导致挂起时间,因为它仍然无限期地处理。

所以要解决这个问题:

p.StartInfo.RedirectStandardoutput = False
p.StartInfo.RedirectStandarderror = False

答案 16 :(得分:0)

我认为这是一种简单而且更好的方法(我们不需要AutoResetEvent):

public static string GGSCIShell(string Path, string Command)
{
    using (Process process = new Process())
    {
        process.StartInfo.WorkingDirectory = Path;
        process.StartInfo.FileName = Path + @"\ggsci.exe";
        process.StartInfo.CreateNoWindow = true;
        process.StartInfo.RedirectStandardOutput = true;
        process.StartInfo.RedirectStandardInput = true;
        process.StartInfo.UseShellExecute = false;

        StringBuilder output = new StringBuilder();
        process.OutputDataReceived += (sender, e) =>
        {
            if (e.Data != null)
            {
                output.AppendLine(e.Data);
            }
        };

        process.Start();
        process.StandardInput.WriteLine(Command);
        process.BeginOutputReadLine();


        int timeoutParts = 10;
        int timeoutPart = (int)TIMEOUT / timeoutParts;
        do
        {
            Thread.Sleep(500);//sometimes halv scond is enough to empty output buff (therefore "exit" will be accepted without "timeoutPart" waiting)
            process.StandardInput.WriteLine("exit");
            timeoutParts--;
        }
        while (!process.WaitForExit(timeoutPart) && timeoutParts > 0);

        if (timeoutParts <= 0)
        {
            output.AppendLine("------ GGSCIShell TIMEOUT: " + TIMEOUT + "ms ------");
        }

        string result = output.ToString();
        return result;
    }
}

答案 17 :(得分:0)

我认为使用异步,即使同时使用standardOutput和standardError,也可能有一个更优雅的解决方案并且没有死锁:

using (Process process = new Process())
{
    process.StartInfo.FileName = filename;
    process.StartInfo.Arguments = arguments;
    process.StartInfo.UseShellExecute = false;
    process.StartInfo.RedirectStandardOutput = true;
    process.StartInfo.RedirectStandardError = true;

    process.Start();

    var tStandardOutput = process.StandardOutput.ReadToEndAsync();
    var tStandardError = process.StandardError.ReadToEndAsync();

    if (process.WaitForExit(timeout))
    {
        string output = await tStandardOutput;
        string errors = await tStandardError;

        // Process completed. Check process.ExitCode here.
    }
    else
    {
        // Timed out.
    }
}

这是基于Mark Byers的回答。 如果您不在异步方法中,则可以使用string output = tStandardOutput.result;代替await

答案 18 :(得分:0)

我已经阅读了许多答案,并做出了自己的答案。不确定在任何情况下都可以解决此问题,但可以在我的环境中解决此问题。我只是不使用WaitForExit,而是在输出和错误结束信号上都使用WaitHandle.WaitAll。如果有人看到可能的问题,我将感到高兴。还是会帮助某人。对我来说更好,因为不使用超时。

private static int DoProcess(string workingDir, string fileName, string arguments)
{
    int exitCode;
    using (var process = new Process
    {
        StartInfo =
        {
            WorkingDirectory = workingDir,
            WindowStyle = ProcessWindowStyle.Hidden,
            CreateNoWindow = true,
            UseShellExecute = false,
            FileName = fileName,
            Arguments = arguments,
            RedirectStandardError = true,
            RedirectStandardOutput = true
        },
        EnableRaisingEvents = true
    })
    {
        using (var outputWaitHandle = new AutoResetEvent(false))
        using (var errorWaitHandle = new AutoResetEvent(false))
        {
            process.OutputDataReceived += (sender, args) =>
            {
                // ReSharper disable once AccessToDisposedClosure
                if (args.Data != null) Debug.Log(args.Data);
                else outputWaitHandle.Set();
            };
            process.ErrorDataReceived += (sender, args) =>
            {
                // ReSharper disable once AccessToDisposedClosure
                if (args.Data != null) Debug.LogError(args.Data);
                else errorWaitHandle.Set();
            };

            process.Start();
            process.BeginOutputReadLine();
            process.BeginErrorReadLine();

            WaitHandle.WaitAll(new WaitHandle[] { outputWaitHandle, errorWaitHandle });

            exitCode = process.ExitCode;
        }
    }
    return exitCode;
}

答案 19 :(得分:0)

这些答案都没有帮助我,但是此解决方案可以很好地处理挂起

https://stackoverflow.com/a/60355879/10522960

答案 20 :(得分:-1)

让我们将这里发布的示例代码称为重定向器,并将另一个程序重定向。如果是我,那么我可能会写一个测试重定向程序,该程序可以用来重现该问题。

所以我做到了。对于测试数据,我使用了ECMA-334 C#语言规范v PDF;它大约是5MB。以下是其中的重要部分。

StreamReader stream = null;
try { stream = new StreamReader(Path); }
catch (Exception ex)
{
    Console.Error.WriteLine("Input open error: " + ex.Message);
    return;
}
Console.SetIn(stream);
int datasize = 0;
try
{
    string record = Console.ReadLine();
    while (record != null)
    {
        datasize += record.Length + 2;
        record = Console.ReadLine();
        Console.WriteLine(record);
    }
}
catch (Exception ex)
{
    Console.Error.WriteLine($"Error: {ex.Message}");
    return;
}

datasize值与实际文件大小不匹配,但这无关紧要。目前尚不清楚PDF文件是否始终在行尾使用CR和LF,但这无关紧要。您可以使用任何其他大型文本文件进行测试。

使用示例重定向器代码在我写入大量数据时挂起,而在我写入少量数据时不挂起。

我非常努力地以某种方式跟踪该代码的执行,但我做不到。我对重定向程序的各行进行了注释,这些行禁止为重定向程序创建控制台以尝试获取单独的控制台窗口,但我做不到。

然后我发现了How to start a console app in a new window, the parent’s window, or no window。因此,很明显,当一个控制台程序在没有ShellExecute的情况下启动另一个控制台程序时,我们不能(轻松地)拥有一个单独的控制台,并且由于ShellExecute不支持重定向,即使我们未为其他进程指定窗口,我们也必须共享一个控制台。

我认为,如果重定向的程序在某个地方填满了缓冲区,则它必须等待读取数据,并且如果此时重定向程序没有读取任何数据,则它是一个死锁。

解决方案是不使用ReadToEnd并在写入数据时读取数据,但是不必使用异步读取。解决方案可能非常简单。以下内容适用于5 MB PDF。

ProcessStartInfo info = new ProcessStartInfo(TheProgram);
info.CreateNoWindow = true;
info.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden;
info.RedirectStandardOutput = true;
info.UseShellExecute = false;
Process p = Process.Start(info);
string record = p.StandardOutput.ReadLine();
while (record != null)
{
    Console.WriteLine(record);
    record = p.StandardOutput.ReadLine();
}
p.WaitForExit();

另一种可能性是使用GUI程序进行重定向。上面的代码在WPF应用程序中有效,除非进行了明显的修改。

答案 21 :(得分:-3)

我遇到了同样的问题,但原因不同了。但它会在Windows 8下发生,但不会在Windows 7下发生。以下行似乎导致了问题。

pProcess.StartInfo.UseShellExecute = False

解决方案是不禁用UseShellExecute。我现在收到一个Shell弹出窗口,这是不需要的,但比等待没有特别发生的程序要好得多。所以我为此添加了以下解决方法:

pProcess.StartInfo.WindowStyle = ProcessWindowStyle.Hidden

现在唯一困扰我的是为什么在Windows 8下首先发生这种情况。