Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 926
Pavel Voronin Avatar asked Apr 01 '13 12:04

Pavel Voronin


1 Answers

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?

like image 96
greg84 Avatar answered Oct 07 '22 13:10

greg84