为什么 Console.In.ReadLineAsync 会阻塞? [英] Why does Console.In.ReadLineAsync block?

查看:26
本文介绍了为什么 Console.In.ReadLineAsync 会阻塞?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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 被阻塞并且直到在控制台中输入一行才会返回..所以嗨"永远不会被写入控制台.

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.

在 Console.In.ReadLineAsync 上使用 await 也会阻塞.

Using await on Console.In.ReadLineAsync also blocks.

据我所知,新的 Async CTP 方法不会阻塞.

It was my understanding that the new Async CTP methods do not block.

这是什么原因?

这是另一个例子

static void Main(string[] args)
{
    Task delayTask = Task.Delay(50000);

    Debug.WriteLine("hi");
}

这符合我的预期,它直接进入下一行并打印hi",因为 Task.Delay 不会阻塞.

This behaves as I expect, it goes straight to the next line and prints "hi" since Task.Delay does not block.

推荐答案

daryal 在这里提供了答案http://smellegantcode.wordpress.com/2012/08/28/无聊的发现/

daryal provided the answer here http://smellegantcode.wordpress.com/2012/08/28/a-boring-discovery/

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

It seems ReadLineAsync is not actually doing what it's supposed to do. Bug in the framework.

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

My solution is to use ThreadPool.QueueUserWorkItem in a loop so each call to ReadLineAsync is done on a new thread.

这篇关于为什么 Console.In.ReadLineAsync 会阻塞?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆