gpt4 book ai didi

c# - 为什么 Console.In.ReadLineAsync 会阻塞?

转载 作者:可可西里 更新时间:2023-11-01 09:09:01 33 4
gpt4 key购买 nike

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

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

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

Console.In.ReadLineAsync 处于阻塞状态,直到在控制台中输入一行后才会返回。因此“Hi”永远不会写入控制台。

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

据我了解,新的 Async CTP 方法不会阻塞。

这是什么原因?


还有一个例子

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

Debug.WriteLine("hi");
}

这如我所料,它直接进入下一行并打印“hi”,因为 Task.Delay 不会阻塞。

最佳答案

daryal 在这里提供了答案 http://smellegantcode.wordpress.com/2012/08/28/a-boring-discovery/

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

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

关于c# - 为什么 Console.In.ReadLineAsync 会阻塞?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14724582/

33 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com