HOWTO Read from stdout without blocking.
Please help,
I have an app that is launching another process, where it is letting the new
process inherit the STD-IN/OUT hanldes. The goal is to let the C# app use
STDOUT to get feedback from the app after it starts. The problem is that the
reading of STDOUT is blocking when the "EndRead" is called as such:
============================================
public System.Diagnostics.Process Process_MyApp = null;
// Process_MyApp is initialized...
public string ReadStdOut(int iLen, int iMaxTime)
{
if (StreamReader_StdOut == null)
{
ERR =
"The STD-OUT stream is not active at the moment and can not be read at
this time";
throw(new Exception(ERR));
}
DateTime DateTime_Start = DateTime.Now;
TimeSpan TimeSpan_Temp;
byte[] zbyteTemp = new byte[1];
System.IAsyncResult IAsyncResult_Temp;
string csBYTE;
string csRET = "";
for
(
TimeSpan_Temp = DateTime.Now - DateTime_Start,
IAsyncResult_Temp = StreamReader_StdOut.BaseStream.BeginRead
(
zbyteTemp, 0, 1, null, null
);
((iMaxTime > 0) && (TimeSpan_Temp.TotalSeconds < iMaxTime)) &&
!Process_MyApp.HasExited;
TimeSpan_Temp = DateTime.Now - DateTime_Start,
IAsyncResult_Temp = StreamReader_StdOut.BaseStream.BeginRead
(
zbyteTemp, 0, 1, null, null
)
)
{
StreamReader_StdOut.BaseStream.EndRead(IAsyncResul t_Temp); // This
blocks!!!!
if (IAsyncResult_Temp.IsCompleted)
{
csBYTE = "";
csBYTE += Convert.ToChar(zbyteTemp[0]);
csRET += csBYTE;
if (iLen > 0)
{
if (csRET.Length >= iLen)
{
break;
}
}
else
{
if (csBYTE == "\n")
{
break;
}
}
}
System.Threading.Thread.Sleep(50);
}
if ((iMaxTime > 0) && (TimeSpan_Temp.TotalSeconds > iMaxTime))
{
ERR =
"MyApp failed to start and return the expect RET code within " +
iMaxTime.ToString() + " " +
"seconds. MyApp may be hung and/or corrupt, and may require one to
manually " +
"stop the MyApp's process via the task manager";
throw(new Exception(ERR));
}
if (Process_MyApp.HasExited)
{
throw(new Exception("MyApp object has exited"));
}
return csRET;
}