Skip to content

Async Console Read Cannot Be Cancelled #100308

Open
@grochoge

Description

@grochoge

Description

After beginning an asynchronous stream read of standard input (on Windows at least) with a cancellation token, cancelling the token does not cancel the read.

Reproduction Steps

using System.Threading;
var cancel = new CancellationTokenSource();
var stdin = Console.OpenStandardInput();
var buffer = new byte[1024];
var read = stdin.ReadAsync( buffer, cancel.Token );
cancel.Cancel();
await read;

Expected behavior

Read is cancelled and a cancellation exception is thrown.

Actual behavior

The await call blocks forever.

Regression?

No response

Known Workarounds

No response

Configuration

.NET 8.0.3
Windows 10 19045.4046

Other information

A stack trace shows the program calling the regular console read method, not an asynchronous version:

 	System.Console.dll!Interop.Kernel32.ReadFile(nint handle, byte* bytes, int numBytesToRead, out int numBytesRead, nint mustBeZero) Line 412	C#
 	System.Console.dll!System.ConsolePal.WindowsConsoleStream.ReadFileNative(nint hFile, System.Span<byte> buffer, bool isPipe, out int bytesRead, bool useFileAPIs) Line 1150	C#
 	System.Console.dll!System.ConsolePal.WindowsConsoleStream.Read(System.Span<byte> buffer) Line 1108	C#
>	System.Console.dll!System.IO.ConsoleStream.Read(byte[] buffer, int offset, int count) Line 34	C#
 	[Async] Program.Main(string[] aArgs) Line 73	C#

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions