HOWTO Read from stdout without blocking.

G

Guest

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(IAsyncResult_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;
}
 
T

Truong Hong Thi

StreamReader_StdOut.BaseStream.EndRead(IAsyncResult_Temp); // ThisI suggest you try the followings:
- Call Process.WaitForExit() before the blocking line above
- Pass an AsyncCallback for BeginRead, and call EndRead in that
AsyncCallback implementation.

Hope it helps,
Thi
 
G

Guest

Thanks for the reply, but that does not help. At any rate, I've given up on
this approach altogether.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Similar Threads


Top