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

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

问题描述

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

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.

这是我的理解是,新的异步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");
     }

此行​​为如我所料,它直接到下一行并打印喜,因为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:// smellegant code.word press.com / 2012/08/28 / A-镗发现/

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.

我的解决办法是在一个循环,使每次调用ReadLineAsync是在一个新的线程完成使用ThreadPool.QueueUserWorkItem。

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天全站免登陆