HOWTO Make StreamReader class not block.

G

Guest

HOWTO Make StreamReader class not block.

Please help,

I'm trying to use the Std-Out from a process I launch, to read back data
from the process, until either the data I expcet is passed, or a time limit
hgas expired. My problem is that the StreamReader class blocks until the
process writes something. Here is a snippet of code with the problem:

Process_MyProcess = new System.Diagnostics.Process();
ProcessStartInfo_MyProcess = new
System.Diagnostics.ProcessStartInfo();

ProcessStartInfo_MyProcess.FileName = "My Path";
ProcessStartInfo_MyProcess.RedirectStandardInput = true;
ProcessStartInfo_MyProcess.RedirectStandardOutput = true;
ProcessStartInfo_MyProcess.UseShellExecute = false;

Process_MyProcess.StartInfo = ProcessStartInfo_MyProcess;

if (!Process_MyProcess.Start())
{
throw(new Exception("Error"));
}

StreamWriter_StdIn = Process_MyProcess.StandardInput;
StreamWriter_StdIn.Write(csStdIn);

StreamReader_StdOut = Process_MyProcess.StandardOutput;

int iChar, iTotalTimesInSeconds = 0;
DateTime DateTime_Start = DateTime.Now;
TimeSpan TimeSpan_Temp;

// ERROR!
//
// I want to use ReadLine, but that blocks, Even Peek as shown below
blocks...
//
// what can I do?

for
(
TimeSpan_Temp = DateTime.Now - DateTime_Start,
iChar = StreamReader_StdOut.Peek(); <== This blocks!!!!!
((iChar < 0) && (TimeSpan_Temp.TotalSeconds < 30));
TimeSpan_Temp = DateTime.Now - DateTime_Start,
iChar = StreamReader_StdOut.Peek()
)
{
System.Threading.Thread.Sleep(100);
}
 
J

Jon Skeet [C# MVP]

ATS said:
HOWTO Make StreamReader class not block.

Don't - instead, start different threads to read from stderr and
stdout. It's a lot simpler than trying to do it with asynchronous IO
(if that's even possible) and it works pretty well in my experience.
 
G

Guest

Thanks for the reply, but I figured it out. I used the
SteamReader.BaseStream.BeginRead to make it work. Thanks anyways.
 
J

Jon Skeet [C# MVP]

ATS said:
Thanks for the reply, but I figured it out. I used the
SteamReader.BaseStream.BeginRead to make it work. Thanks anyways.

Sorry, I assumed you wanted to actually use the functionality of the
StreamReader - just reading the binary data from the stream doesn't do
that.
 

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

Top