How to interrupt an IO bound thread
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开发者_StackOverflow;
}
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.
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...
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.
精彩评论