A colleague of mine found an issue with our code and it took a while to hunt down exactly what was happening, but it can be best demonstrated by this simple example:
<
I have a suspicion as to what's going on. What I've observed:
ReadKey
, it's fine. This includes fetching Console.Out
but not using itConsole.WriteLine
call starts before the Console.ReadKey
call, it's fine (and you can have multiple WriteLine
calls while ReadKey
is waitingI suspect that the first operation to use the console acquires a lock for initialization (to avoid it being initialized twice) and that the ReadKey
method keeps hold of the lock until a key has been read. That would certainly explain every program I've run so far.
The operations which perform the hypothesized initialization are interesting though - reading Console.Out
"fixes" the issue, but reading from Console.In
doesn't.
I suspect that ReadKey
initializes the output because the value is still echoed to the console... but I wouldn't like to swear to it.
Interestingly, using Console.ReadLine()
instead of Console.ReadKey()
doesn't cause the problem in the first place.
Actually, the first case doesn't fail. "Hello World" appears just before the Application ends. This is a classical Race Condition. In the first case,Console.ReadKey()
from the main thread beats the task, and in the second case, the task wins. Unfortunately, I cannot tell you Exactly why writing the empty string makes the task win.