dotnet/runtime

Console.In.Peek() always returning EOF after the first read line on Windows

Open

#40,735 建立於 2020年8月12日

在 GitHub 查看
 (4 留言) (0 反應) (0 負責人)C# (5,445 fork)batch import
area-System.Consolehelp wantedos-windows

倉庫指標

Star
 (17,886 star)
PR 合併指標
 (平均合併 12天 11小時) (30 天內合併 661 個 PR)

描述

I came across the following behaviour when debugging a System.Console test. Running

static void Main()
{
    while (true)
    {
        Console.Write("Enter some text: ");
        int c = Console.In.Peek();
        string? line = Console.In.ReadLine();
        Console.WriteLine($"Peek: {c} ReadLine: {line}");
    }
}

Produces the following behaviour

Enter some text: test
Peek: 116 ReadLine: test
Enter some text: test
Peek: -1 ReadLine: test
Enter some text: test
Peek: -1 ReadLine: test

Essentially it is impossible to use Console.In.Peek() after the first line has been consumed. Note that this behaviour manifests itself regardless of whether the buffer contains any characters. The following variant will produce the exact same observable behaviour:

static void Main()
{
    while(true)
    {
        Console.Write("Enter some text: ");
        int c = MyPeek();
        string? line = Console.In.ReadLine();
        Console.WriteLine($"Peek: {c} ReadLine: {line}");
    }

    static int MyPeek()
    {
        while (!Console.KeyAvailable)
        {
            Thread.Sleep(10);
        }
        return Console.In.Peek();
    }
}

Note that unix does not have the same behaviour.

貢獻者指南