Click to See Complete Forum and Search --> : (.NET) Thead.Interrupt() doesn't interrupt Console.In.Read()


dchestnutt
June 24th, 2005, 03:26 PM
I'm piping Console.In to another process (started by my main process). In my Thread, I'm doing it character by character, something like this:

[In ThreadStart method]
while ( m_continue ) {
int readChar = Console.In.Read();
m_writer.Write( (char)readChar );
m_writer.Flush();
}

When the subprocess goes away, the main thread does this:

[In main thread]
m_continue = false;
m_thread.Interrupt();

Unfortunately, the thread stays blocked on the Read(). I've tried Thread.Abort(), and that doesn't unblock the Read either.

Any suggestions?
Thanks.

dchestnutt
June 28th, 2005, 08:33 AM
I've found a workaround. It's not general purpose, but it works for my case.

I believe the core of the problem is this: The Read(), in the framework, makes a call to do the actual read in kernel32 (or someplace in unmanaged code). That Read blocks, as expected. The call to Thread.Interrupt() is for managed code only -- it marks the thread as "to be interrupted as soon as it returns to managed code". Of course, that doesn't interrupt the read in the OS, so we never unblock the Read(). Thread.Abort() has the same issue.

I couldn't find a way to directly unblock the read.

However, in my case, I was trying to exit the program and simply shutdown the Read loop. So, here's what I did: I called Environment.Exit(). This has the ability to stop the other thread for me. So, my particular problem is solved, but I still wonder if there's a way to unblock the Read in unmanaged code...

For a description of the managed/unmanaged thread blocking issue, see this link, in the section on "Blocking Issues"
http://msdn.microsoft.com/library/default.asp?url=/library/en-us/cpguide/html/cpconmanagedunmanagedthreadinginmicrosoftwindows.asp