Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
180 views
Welcome To Ask or Share your Answers For Others

1 Answer

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...