c# - 使用 Process 调用可执行文件间歇性崩溃

标签 c# executable

我正在用 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/

相关文章:

c# - EF Core 查询 - 有没有办法按字母顺序查找下一个和上一个项目?

c# - asp.net webapi 绑定(bind) ef 模型与文件

c# - 自定义类型和序列化列表的问题

c# - 按值复制带有 int List <int, List<int>> 的字典

c++ - 是否有针对 32 位可执行文件的具有修改和重组功能的反汇编程序?

c# - 找到包含所有可能的 3x3 位模式的 NxM 网格

powershell - 如何将二进制 blob 附加到 PowerShell 脚本以作为脚本文本被忽略?

linux - ubuntu 上的 Cython 独立可执行文件

java - 使用自定义命令行程序启动 jar

python - 运行 .exe 文件 Python 2.7 时 Pyinstaller Intel MKL fatal error