Stoppable console reading on different thread
Does anybody know how to stop the Console.ReadLine method, when it's running on a different thread?
Right now I use a code (the loop part of it) that works like this:
while (true)
{
while (!Console.KeyAvailable) Thread.Sleep(100);
开发者_如何转开发 string line = Console.ReadLine();
}
It does work, but the problem is that as soon as I type a single character, the server won't shutdown.
Does anybody know how to achieve this? (Completely different approaches welcome too, as long as it allows me to read console lines, after I call a Start() method, and that it stops after a Stop() method call.)
Console.ReadLine
calls TextReader.ReadLine
internally. This exits if the underlying stream is closed. If you call Console.In.Close()
from the main thread it might work or you may not be able to close the console input stream. Try it and see.
Forget it, Console.In.Close() seems to be a no-op.
Update
This post has all sorts of methods for doing something very similar: How to add a Timeout to Console.ReadLine()?
(Deleted code because it didn't work)
Another update
I did some more research and this is what I found:
The console is in line mode.
The user cannot enter text in line mode until Read, ReadLine or Peek has been called.
Read, ReadLine and Peek block until the user has pressed Enter.
Hence we cannot let the console handle line input or we get the blocking problem.
So we must use KeyAvailable and ReadKey and manage deletions, etc. ourselves
This article has an example of handling ReadKey input: http://msdn.microsoft.com/en-us/library/system.consolekeyinfo.keychar.aspx
If you amend this function to always call KeyAvailable before calling ReadKey and sleep briefly if there's no input you can avoid blocking.
Set the IsBackground property to true for the thread that is running this loop. That should allow the CLR to shutdown the application cleanly.
Use KeyAvailable and ReadKey instead of ReadLine. Or possibly call Thread.Abort on the console consumer thread.
精彩评论