Skip to content

nuskey8/AsyncConsoleReader

Repository files navigation

AsyncConsoleReader

Provides a cancelable, non-blocking alternative to Console.Read()/ReadKey()/ReadLine().

NuGet Releases license

English | 日本語

Overview

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.

Installation

NuGet packages

To use AsyncConsoleReader, .NET 8.0 or higher is required. Packages can be obtained from NuGet.

.NET CLI

dotnet add package AsyncConsoleReader

Package Manager

Install-Package AsyncConsoleReader

Usage

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);

License

This library is provided under the MIT License.

About

Provides a cancelable, non-blocking alternative to Console.Read / ReadKey / ReadLine

Resources

License

Stars

Watchers

Forks

Packages

No packages published

Languages