C# 为什么Console.In.ReadLineAsync会被阻止?

C# 为什么Console.In.ReadLineAsync会被阻止?,c#,async-await,C#,Async Await,使用以下代码启动新的控制台应用程序- class Program { static void Main(string[] args) { while (true) { Task<string> readLineTask = Console.In.ReadLineAsync(); Debug.WriteLine("hi"); } } } 这和我预期的一样,它直接进

使用以下代码启动新的控制台应用程序-

class Program
{
    static void Main(string[] args)
    {
        while (true)
        {
            Task<string> readLineTask = Console.In.ReadLineAsync();

            Debug.WriteLine("hi");
        }
    }
}

这和我预期的一样,它直接进入下一行并打印“hi”,因为任务。延迟不会阻塞。

daryal在这里提供了答案

看起来ReadLineAsync实际上并没有做它应该做的事情。框架中的Bug

我的解决方案是在循环中使用ThreadPool.QueueUserWorkItem,这样每次对ReadLineAsync的调用都在一个新线程上完成。

现在可以在以下内容中找到:

标准输入流上的读取操作同步执行。也就是说,它们会阻塞,直到指定的读取操作完成。即使对属性返回的对象调用了异步方法(如)也是如此

另一个解决方案:

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");
}
这里报告了这个错误
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");
}