Why does Console.ReadKey() block output of Console.WriteLine called in another thread?

元气小坏坏 提交于 2019-12-19 18:55:41

问题


I have a very simple console app.

static void Main(string[] args)
{
    DoAsync();
    Console.ReadKey();
}

Here DoAsync starts set of task and returns not waiting for tasks' completition. Each task writes to Console, but the ouptut is not shown before key is pressed.
When I use Console.ReadLine everything works fine.

So I'm curious about ReadKey() pecularities.


回答1:


From the documentation for Console.ReadKey():

The ReadKey method waits, that is, blocks on the thread issuing the ReadKey method, until a character or function key is pressed.

What it actually does is acquire a lock on Console.InternalSyncObject, which prevents further operations on the console.

The Console.ReadLine() method does not block the thread in this way.

Reading this article I'm guessing you have .NET 4.5 installed?



来源:https://stackoverflow.com/questions/15743717/why-does-console-readkey-block-output-of-console-writeline-called-in-another-t

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!