views:

28

answers:

2

I am opening a System.Diagnostic.Process to read the stdout from a process and I would like to be able to interrupt it after a certain elapsed time.

try
{
    output = outputStream.ReadToEnd();
}
catch (ThreadInterruptedException e)
{
    return;
}

That doesn't work since the thread is in the ReadToEnd() method. I attempted to close the stream from the main thread, hoping that'd EOF the Read method, but that didn't work either.

A: 

I would hazard aborting

try 
{ 
    Timer watchdog = new Timer(abortMe, Thread.CurrentThread, timeout, Timeout.Infinite);
    output = outputStream.ReadToEnd(); 
    watchdog.Dispose();
} 
catch (ThreadAbortException e) 
{ 
    return; 
} 

private void abortMe(object state)
{
    ((Thread)state).Abort()
}

Actually I succeed in closing the stream when I work with TCP and UDP sockets: it triggers a SocketException and the thread gets successfully interrupted.

By the way, should your stream be an input stream? You're not supposed to read an output stream...

djechelon
whoops. Since I'm reading the standard out, I named it output. A watchdog is exactly what I have, but it doesn't work. `static void doExit(object o){ foreach (object thread in threads) { ((Thread)thread).Abort(); }}`
Novikov
A: 

You could try calling Dispose() on the Process object as well as on the stream. I imagine outputStream is linked to the Process instance via Process.StandardOutput so this ought to have the desired effect.

EDIT - see my answer to this question - this area of .Net I/O is prone to deadlocking, prefer async I/O if that is an option.

Steve Townsend