我有一个C# winform应用程序,其中的优化模型由OR工具解决。优化求解器具有发送整个优化过程的能力,因为stdout.This是通过以下方式完成的:
Slvr.EnableOutput();
Solver.ResultStatus restatus = Slvr.Solve(); 但是,解算器不会自动打开控制台。目前,我所做的是:
项目属性-->应用程序-->输出类型-->控制台应用程序
并且控制台从应用程序运行的开始到结束都是准备好的。因此,会自动显示进程stdout。
我想要的是在运行上述部分代码时打开控制台,并显示求解器中的stdout。然后等待用户按键关闭控制台并继续主应用程序。
发布于 2019-09-01 01:07:06
我猜您的问题是您试图将求解器作为Winforms应用程序的一部分,在GUI进程中运行,对吗?但在Winforms应用程序中,Console输出通常是禁用的。你基本上有两个选择:
Winforms application
System.Diagnostics.Process.Start将命令行部分作为单独的进程运行,这允许对输出重定向进行细粒度控制。您可能需要UI将参数传递到命令行程序,例如,通过使用临时文件。第二个选项是更多的工作,特别是对于GUI和命令行工具之间的通信,但是可以通过GUI不被阻塞的方式更容易地实现,对求解器部分中的bug/程序崩溃更加健壮,并且在您想要引入并行化/同时运行多个求解器进程的情况下通常执行得更好。
发布于 2021-02-17 23:11:08
Brown博士已经回答了您的问题,我添加这个只是为了提供一些代码,说明我们是如何在这里实现它的--这正是他所建议的。我们有一个单独的testPlugin.exe,从这里开始。通信是通过在文件系统上读取和写入的文件进行的。控制台输出在“输出处理程序”中被捕获
using System;
using System.Diagnostics;
using System.IO;
...
private void startTest()
{
int result = 2;
setFormStatus("working..."); // My method to inform the user with the form to wait.
getFormData(); // My method to get the data from the form
string errorMessage = null;
System.Diagnostics.Process testPlugInProcess = new System.Diagnostics.Process();
try
{
using (testPlugInProcess)
{
testPlugInProcess.StartInfo.UseShellExecute = false;
testPlugInProcess.StartInfo.FileName = System.IO.Path.Combine(assemblyDirectory, TestPlugInExe); // The name of the exe file
testPlugInProcess.StartInfo.CreateNoWindow = false;
testPlugInProcess.StartInfo.Arguments = getModelTestCommandLineArgs(); // My method to create the command line arguments
testPlugInProcess.StartInfo.RedirectStandardError = true;
testPlugInProcess.StartInfo.RedirectStandardOutput = true;
testPlugInProcess.OutputDataReceived += pluginTestOutputHandler;
testPlugInProcess.ErrorDataReceived += pluginTestOutputHandler;
testPlugInProcess.Start();
testPlugInProcess.BeginErrorReadLine();
testPlugInProcess.BeginOutputReadLine();
testPlugInProcess.WaitForExit();
result = testPlugInProcess.ExitCode;
}
setFormStatus("");
}
catch (Exception ex)
{
errorMessage = ex.Message;
}
testPlugInProcess = null;
}在这里,控制台和错误输出都写入到同一个文件中,但您可以将它们分开。
插件处理程序如下所示:
private static void pluginTestOutputHandler(object sendingProcess,
DataReceivedEventArgs outLine)
{
if (!String.IsNullOrEmpty(outLine.Data))
{
for (int i = 0; i < numberOfTriesForWriting; i++)
{
try
{
using (StreamWriter sw = File.AppendText(lastPlugInTestTraceFilePath)) // The file name where the data is written.
{
sw.WriteLine(outLine.Data);
sw.Flush();
return;
}
}
catch (IOException)
{
System.Threading.Thread.Sleep(msToWaitBetweenTries);
}
}
}
}https://stackoverflow.com/questions/57739813
复制相似问题