System.Console.In.Peek() behavior?

  • Thread starter Thread starter Peter Andersen
  • Start date Start date
P

Peter Andersen

Please take a look at the following (more or less
nonsense) program.

I am trying to understand the exact behavior of
System.Console.In.Peek().
Does it block when no input is available?
From the documentation I would expect it not to block but
instead return -1.
However the first call to Peek() below seems to block -
no dots are written to the console.
Strangely enough, if you enter a text followed by return,
and then let the first call of ReadLine() "eat" all this,
I would expect to be in the same situation as at program
start up. However, this second call does not block, but
immediately returns -1 (dots appear in the output).
Whats worse - even if I type something followed by
return, this input is never detected by the sequence of
Peek() calls in the second while loop - I never get out
of it.
Am I overlooking something, or is there a bug in the .NET
framework?


peek.cs:
========

using System;
using System.IO;
using System.Threading;

public class test {
public static void Main(System.String[] args)
{
Console.Write("Enter some text: ");
// first peek will block!!
while (Console.In.Peek() == -1){
// we never get here
Console.Write('.'); Thread.Sleep(500);
}
Console.WriteLine("Input 1 available:
+ "Console.ReadLine());

Console.Write("Enter some more text: ");
// second peek is non-blocking,
// but never detects input!!
while (Console.In.Peek() == -1){
// we never get out of this loop
Console.Write('.'); Thread.Sleep(500);
}
Console.WriteLine("Input 2 available: "
+ Console.ReadLine());
}
}


Typical cmd session:
=====================

C:\>csc -t:exe -nologo peek.cs

C:\>.\peek
Enter some text: lklklklkl
Input 1 available: lklklklkl
Enter some more text: .............^C
C:\>lklklklkl
'lklklklkl' is not recognized as an internal or external
command,
operable program or batch file.

No dots appear despite waiting to respond to the first
prompt.
Input typed while the dots stream out of the second loop
is not detected by the program, but first after the
program is killed (here using Control-C)


Peter Andersen
 
Am I overlooking something, or is there a bug in the .NET
framework?

Looks like a bug to me. I'd personally expect there to also be a
blocking version of Peek available or an extra "special" return code so
that it would be easy to tell the difference between end-of-stream and
"nothing available right now".
 
Back
Top