本文介绍了Process.WaitForExit()触发太快的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

下面是code我用它来运行C#code的extern可执行文件(非托管):

Here is the code I use to run extern executable (unmanaged) from c# code:

static void Solve()
            {
                Process newProc = new Process();
                newProc.StartInfo.WorkingDirectory =  Path.Combine(Directory.GetCurrentDirectory(), "Data");
                newProc.StartInfo.FileName = "solver.exe";
                newProc.StartInfo.CreateNoWindow = true;
                newProc.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
                try
            {
                newProc.Start();
                newProc.WaitForExit();

            }
            catch (Exception e)
            {
            StreamWriter errorReporter = new StreamWriter("ErrorLog.txt", true);
    errorReporter.WriteLine(message);
    errorReporter.Close();

            }
            newProc.Close();
        }

在我的情况下,解算器30秒左右,如果我手动启动它。 solver.exe行动的结果是一个文件。但是,当我要求它从code,退出几乎在同一时刻,什么都不做。没有输出来自它时,不产生输出文件。

In my case solver works about 30 seconds if I start it manually. The result of solver.exe actions is a file. But when I call for it from code, it exits almost the same moment and does nothing. No output comes from it, output file is not generated.

此外,过程正确启动,没有错误抛出。有没有在code以上的任何问题,或者我应该只是开始检查solver.exe?

Also, process is started correctly, no errors are thrown. Is there any problems in the code above or should I just start with checking solver.exe?

推荐答案

您进程可能失败在无法预料的方式。你可以只知道读输出和错误流,并将其存储在一个文件中(或写入到控制台或事件日志)

Your process is probably failing in an unforeseen way. You can only know to read the Output and Error stream and store it in a file (or write it to the console, or eventlog)

请记住,如果你需要读取错误和输出simultanuously流做异步/事件驱动。否则,流将被阻塞,不会产生任何输出或者不是你后的输出。

Remember that if you need to read the Error AND the Output streams simultanuously to do it async/eventdriven. Otherwise the streams will block and not produce any output or not the output you're after.

StreamWriter errorReporter = new StreamWriter("SOLVER-OUTPUT-ERROR.txt", true);

newproc.StartInfo.RedirectStandardOutput = true;
newproc.StartInfo.RedirectStandardError = true;

newproc.OutputDataReceived += (sender, args) => errorReporter.WriteLine(args.Data);
newproc.ErrorDataReceived += (sender, args) => errorReporter.WriteLine(args.Data);
newproc.StartInfo.UseShellExecute=false;

newProc.Start();
newProc.BeginOutputReadLine();
newProc.BeginErrorReadLine();

newProc.WaitForExit();

errorReporter.Close();

这篇关于Process.WaitForExit()触发太快的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-23 05:10