我正在用 C# 调用可执行文件。当可执行文件运行时,它会写入控制台,以便 C# 代码获取控制台输出并将其写入文本文件。当崩溃发生时,会发生一些事情。
1) 文本文件的输出未完全写出。 2) 可执行进程似乎完全运行完毕,因为它生成了一个报告,就像成功运行一样。
我怀疑这次崩溃的原因是我写文件的方式。
更新: - 就崩溃而言,会出现一个对话框,显示“管理器遇到问题,需要关闭。对于给您带来的不便,我们深表歉意。”然后它有一个确定按钮。当您单击“确定”时,会出现一个我设置的对话框,询问我是否要再次启动管理器。
- 调用可执行文件的管理器应用程序是单线程的。可执行文件可以多线程运行。
以下是调用的一小段代码:
// Set up process to redirect standard output and standard error to
// a file.
process.StartInfo.UseShellExecute = false;
process.StartInfo.RedirectStandardOutput = true;
process.StartInfo.RedirectStandardError = true;
FileInfo ofi = new FileInfo(outputPath);
FileStream ofs = ofi.OpenWrite();
StreamWriter sw = new StreamWriter(ofs);
WriteToTextWriterEventHandler wtsweh = new WriteToTextWriterEventHandler(sw);
DataReceivedEventHandler handler = wtsweh.HandleDataReceived;
process.OutputDataReceived += handler;
process.ErrorDataReceived += handler;
//
statusAcceptor.ReportStatus("Running process.");
process.Start();
process.BeginOutputReadLine();
process.BeginErrorReadLine();
statusAcceptor.ReportStatus("Waiting for process to complete.");
process.WaitForExit();
int processExitCode = process.ExitCode;
process.Close();
sw.Close();
//
private class WriteToTextWriterEventHandler
{
private TextWriter tw;
public WriteToTextWriterEventHandler(TextWriter tw)
{
this.tw = tw;
}
public void HandleDataReceived(object sendingProcess,
DataReceivedEventArgs outLine)
{
// Collect the sort command output.
if (!String.IsNullOrEmpty(outLine.Data))
{
tw.Write(Environment.NewLine + outLine.Data);
}
}
}
最佳答案
尝试在 tw.Write 之后添加刷新。这应该会导致生成直到故障点的完整输出,其中可能包括来自可执行文件的错误消息(如果这就是崩溃的原因?)
关于c# - 使用 Process 调用可执行文件间歇性崩溃,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/354004/