![](/img/trans.png)
[英]How to asynchronously read the standard output stream and standard error stream at once
[英]How to asynchronously redirect ONLY standard error stream and not standard output stream of a process in C#, .net
我正在用C#編寫一個應用程序,該應用程序有時使用帶有異步IO重定向的Process類將應用程序作為子進程啟動,如下所示:
private void AppLaunch_Click(object sender, RoutedEventArgs e)
{
Process appProcess = new Process();
appProcess.StartInfo.FileName = currAppPath;
appProcess.StartInfo.Arguments = "";
//Setup Redirection
appProcess.StartInfo.UseShellExecute = false;
appProcess.StartInfo.ErrorDialog = false;
appProcess.StartInfo.RedirectStandardError = true;
appProcess.EnableRaisingEvents = true;
// Attach Output Handler
appProcess.ErrorDataReceived += appProc_DataReceived;
appProcess.Exited += appProc_Exited;
buildLogConsoleOutputTxtbox.AppendText(currAppPath + "\n");
appProcess.Start();
appProcess.BeginErrorReadLine();
}
private void appProc_DataReceived(object sender, DataReceivedEventArgs e)
{
if (!String.IsNullOrEmpty(e.Data))
{
this.appendLogText(e.Data);
}
}
private void appProc_Exited(object sender, System.EventArgs e)
{
Process proc = (Process)sender;
// Wait a short while to allow all console output to be processed and appended
Thread.Sleep(40);
this.appendLogText("\n>>");
proc.Close();
}
private void appendLogText(string logText)
{
// Use a delegate if called from a different thread,
// else just append the text directly
if (buildLogConsoleOutputTxtbox.Dispatcher.CheckAccess())
{
// Thread owns the TextBox
buildLogConsoleOutputTxtbox.AppendText(logText + Environment.NewLine);
}
else
{
//Invocation Required
appendLogCallBack appendLog = new appendLogCallBack(buildLogConsoleOutputTxtbox.AppendText);
buildlogScrollEnd buildlogscrl = new buildlogScrollEnd(buildLogConsoleOutputTxtbox.ScrollToEnd);
buildLogConsoleOutputTxtbox.Dispatcher.BeginInvoke(appendLog, new object[] { logText + Environment.NewLine });
buildLogConsoleOutputTxtbox.Dispatcher.BeginInvoke(buildlogscrl);
}
這段代碼的問題在於,盡管我確實將stderr正確地重定向到了我的文本框,但是這種重定向似乎隱藏了進程的stdout輸出,我不想將其重定向!
如果我重定向了stdout,我可以看到它正確地重定向了,但是僅重定向stderr而不是stdout是不可能的嗎? 我到處尋找有關此主題的信息,但所有討論似乎都是關於重定向stdout ...這樣的: 如何立即異步讀取標准輸出流和標准錯誤流
對此我將不勝感激!
這是不可能的-輸出和錯誤句柄被同時重定向。 MSDN文章STARTUPINFO描述了STARTF_USESTDHANDLES
標志。
但是有個好消息。 仍然可以保留子進程的輸出。 您只需要:
所以在流程開始調用之后
[DllImport("Kernel32.dll", SetLastError = true) ]
static extern uint AttachConsole(int pid);
然后在您的DataReceived
處理程序中使用簡單的Console.WriteLine。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.