Skip to content

System.Console should provide a GetCursorPosition property to get the position atomically #28535

@damageboy

Description

@damageboy

Currently, the System.Console class in provides two separate properties, CursorLeftand CursorTop that allow the user to change / read the position of the console cursor.

Unfortunately, there seems to be no public API that allows reading the cursor position "atomically" (e.g. both row and column position) although the underlying implementation does get/set the actual position atomically.

Conversly, there does exist a SetCursorPosition public method:
https://github.com/dotnet/corefx/blob/eec001d96a68376c0e504eb7635c8edec196f90f/src/System.Console/src/System/Console.cs#L306

Rational and Usage

The idea would be to be able to read the cursor position on its associated terminal/console in one atomic API call, unlike today, where users of the Console class often write code like:

  var oldX = Console.CursorLeft;
  var oldY = Console.CursotTop;
  Console.SetCursorPosition(0, oldY + 10);
  // Some console output goes out here
  Console.SetCursorPosition(oldX, oldY);

The proposed API would allow reading/setting the position in one API call that would also translate as one atomic system call / write to the underlying OS:

  Console.GetCursorPosition(out var oldX, out var oldY);
  Console.SetCursorPosition(0, oldY + 10);
  // Some console output goes out here
  Console.SetCursorPosition(oldX, oldY);

The proposed change makes reading the console cursor position more readable, efficient (more on that later) and most importantly atomic, in the sense that the API will allow to ensure that the console cursor is/was in the reported position, unlike today, where the console cursor position can change in between calls to the getters/setters of CursorLeft and CursorTop.

Proposed API

namespace System
{
    public static class Console 
    {
        void GetCursorPosition(out int left, out int top);
    }
}

Details

Metadata

Metadata

Assignees

Labels

Type

No type

Projects

No projects

Relationships

None yet

Development

No branches or pull requests

Issue actions