dotnet / runtime

.NET is a cross-platform runtime for cloud, mobile, desktop, and IoT apps.
https://docs.microsoft.com/dotnet/core/
MIT License
15.25k stars 4.73k forks source link

Console.GetCursorPosition behaves oddly with multiple threads on WSL #109440

Open liamt19 opened 1 day ago

liamt19 commented 1 day ago

Description

Reproduction Steps

static void Main(string[] args)
{
    Task.Run(() =>
    {
        while (true)
        {
            Console.WriteLine($"CursorPosition = {Console.GetCursorPosition()}");
            Thread.Sleep(1000);
        }
    });

    for (int i = 0; i < 10; i++)
    {
        string? input = Console.ReadLine();

        if (i == 2)
        {
            Console.GetCursorPosition();
            Console.GetCursorPosition();
        }
    }
}

Expected behavior

"CursorPosition = ..." should be printed every second, or remain blocked until the calls to Console.ReadLine() complete.

Actual behavior

In each iteration of the loop, nothing is printed until a string is read from Console.ReadLine(). However, once Console.GetCursorPosition() is called twice in the same iteration of the loop, the "CursorPosition = ..." line is printed every second as expected.

For example, CursorPosition = ... is only outputted after a new line is inputted, but after the GetCursorPosition lines are executed, the output continues without anything having been entered:

the
CursorPosition = (0, 2)
quick
CursorPosition = (0, 4)
brown
CursorPosition = (0, 6)
CursorPosition = (0, 7)
CursorPosition = (0, 8)
CursorPosition = (0, 9)

Moving one of the GetCursorPosition calls before the Console.ReadLine produces the same result as when both calls are done after the Console.ReadLine:

for (int i = 0; i < 10; i++)
{
    Console.GetCursorPosition();
    string? input = Console.ReadLine();
    if (i == 2)
        Console.GetCursorPosition();
}

Note the i == 2 can be any number (and the loop max is irrelevant), this is only to show behavior is consistent before GetCursorPosition is called a second time.

Regression?

No response

Known Workarounds

No response

Configuration

Other information

No response

dotnet-policy-service[bot] commented 1 day ago

Tagging subscribers to this area: @dotnet/area-system-console See info in area-owners.md if you want to be subscribed.