Start a new console app using the following code -
class Program
{
static void Main(string[] args)
{
while (true)
{
Task<string> readLineTask = Console.In.ReadLineAsync();
Debug.WriteLine("hi");
}
}
}
Console.In.ReadLineAsync is blocking and doesn't return until a line is entered in the console.. so "Hi" never gets written to the console.
Using await on Console.In.ReadLineAsync also blocks.
It was my understanding that the new Async CTP methods do not block.
What is the reason for this?
Here is another example
static void Main(string[] args)
{
Task delayTask = Task.Delay(50000);
Debug.WriteLine("hi");
}
This behaves as I expect, it goes straight to the next line and prints "hi" since Task.Delay does not block.
One of the most common uses of the ReadLine method is to pause program execution before clearing the console and displaying new information to it, or to prompt the user to press the Enter key before terminating the application.
The key is to wrap Console. ReadLine() in a task.
ReadLine();//it always return string value. Console. WriteLine(s); It gives the string as it is given in the input stream.
The Console. ReadLine() method in C# is used to read the next line of characters from the standard input stream.
Another solution:
static void Main()
{
using (var s = Console.OpenStandardInput())
using (var sr = new StreamReader(s))
{
Task readLineTask = sr.ReadLineAsync();
Debug.WriteLine("hi");
Console.WriteLine("hello");
readLineTask.Wait();// When not in Main method, you can use await.
// Waiting must happen in the curly brackets of the using directive.
}
Console.WriteLine("Bye Bye");
}
daryal provided the answer here http://smellegantcode.wordpress.com/2012/08/28/a-boring-discovery/
It seems ReadLineAsync is not actually doing what it's supposed to do. Bug in the framework.
My solution is to use ThreadPool.QueueUserWorkItem in a loop so each call to ReadLineAsync is done on a new thread.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With