13

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.

Marc
  • 3,905
  • 4
  • 21
  • 37
NoPyGod
  • 4,905
  • 3
  • 44
  • 72

3 Answers3

7

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.

NoPyGod
  • 4,905
  • 3
  • 44
  • 72
4

This can now be found in the documentation:

Read operations on the standard input stream execute synchronously. That is, they block until the specified read operation has completed. This is true even if an asynchronous method, such as ReadLineAsync, is called on the TextReader object returned by the In property.

user247702
  • 23,641
  • 15
  • 110
  • 157
2

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");
}
Ole
  • 56
  • 4