如何解决需要实时读取应用程序输出,但是仅在关闭应用程序后才接收数据
我正试图在应用程序输出数据时准确地实时读取控制台输出数据, 例如...
当我在Windows cmd.exe中运行FramworkDemo.exe时,我可以在1秒内看到字符串“ hello world”, 但是当我使用下面的C#代码运行时,需要30秒...
我只能在控制台应用程序关闭时(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 举报,一经查实,本站将立刻删除。