问题描述
我正试图在应用程序输出数据时准确地实时读取控制台输出数据, 例如...
当我在Windows cmd.exe中运行FramworkDemo.exe时,我可以在1秒内看到字符串“ hello world”, 但是当我使用下面的C#代码运行时,需要30秒...
这就像是锁定控制台以实时检索数据一样。...
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text;
namespace ConsoleApp14
{
class Program
{
class HandleExecutable
{
static private DataReceivedEventHandler outputHandler;
public DataReceivedEventHandler OutputHandler
{
set { outputHandler = value; }
}
static private DataReceivedEventHandler errorHandler;
public DataReceivedEventHandler ErrorHandler
{
set { errorHandler = value; }
}
public void callExecutable(string executable,string args)
{
string commandLine = executable;
processstartinfo psi = new processstartinfo(commandLine);
psi.UseShellExecute = false;
psi.LoadUserProfile = false;
psi.RedirectStandardOutput = true;
psi.RedirectStandardError = true;
psi.WindowStyle = ProcessWindowStyle.Minimized;
psi.CreateNowindow = true;
psi.Arguments = args;
Process p = new Process();
p.StartInfo = psi;
try
{
p.Start();
p.BeginoutputReadLine();
p.BeginErrorReadLine();
if (outputHandler != null) p.OutputDataReceived += outputHandler;
if (errorHandler != null) p.ErrorDataReceived += errorHandler;
p.WaitForExit();
p.Close();
p.dispose();
}
catch (Exception ex)
{
//log.Error(ex.Message);
}
}
}
//On another class
static void p_ErrorDataReceived(object sender,DataReceivedEventArgs e)
{
//HANDLE STDERR
if (e.Data != null && !e.Data.Equals(""))
{
Console.WriteLine(e.Data);
}
}
static void p_OutputDataReceived(object sender,DataReceivedEventArgs e)
{
Console.WriteLine(e.Data);
}
static void Main(string[] argsmain)
{
HandleExecutable he = new HandleExecutable();
he.OutputHandler = p_OutputDataReceived;
he.ErrorHandler = p_ErrorDataReceived;
he.callExecutable(@"C:\prod\bin\App\FramworkDemo.exe","-cp foo ClassName");
Console.ReadKey();
}
}
}
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)