我在 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);
}
}
}