Provides a cancelable, non-blocking alternative to Console.Read()
/ReadKey()
/ReadLine()
.
English | 日本語
AsyncConsoleReader is a library that provides non-blocking standard input reading functionality with CancellationToken
support.
In C#, Console.ReadLine()
is commonly used for reading standard input, but it blocks the process until the reading is complete. Additionally, it cannot be canceled using mechanisms like CancellationToken
. Even if wrapped in Task.Run
, it occupies a thread from the thread pool until the input is finished.
AsyncConsoleReader provides a cancelable implementation of Read/ReadLine
by re-implementing them using Console.ReadKey()
.
It also provides async APIs for efficiently performing reads on the thread pool.
Note
The async APIs of AsyncConsoleReader are helpers for efficiently executing Read()
on background threads. The reading itself is not performed asynchronously.
To use AsyncConsoleReader, .NET 8.0 or higher is required. Packages can be obtained from NuGet.
dotnet add package AsyncConsoleReader
Install-Package AsyncConsoleReader
You can call Read/ReadKey/ReadLine
using AsyncConsole
. These APIs are equivalent to System.Console
but allow cancellation by passing a CancellationToken
.
using AsyncConsoleReader;
var cts = new CancellationTokenSource();
cts.CancelAfter(500);
try
{
var line = AsyncConsole.ReadLine(cts.Token);
Console.WriteLine(line);
}
catch (Exception ex)
{
Console.WriteLine(ex);
}
You can also use the asynchronous API.
var line = await AsyncConsole.ReadKeyAsync(false, cts.Token);
This library is provided under the MIT License.