Closed
Description
I have simple code for the user to retry Console.ReadLine until valid input is given, or the app is terminated, and I noticed that if I call GetCancellationToken
then the user is stuck in the ReadLine loop forever until they give a valid value.
Code:
using System.CommandLine;
namespace ConsoleApp2;
internal class Program
{
static async Task<int> Main(string[] args)
{
var rootCommand = new RootCommand("Test");
rootCommand.SetHandler(async context =>
{
// Uncomment line below, then Ctrl+C will not work anymore.
//var cancellationToken = context.GetCancellationToken();
RunCommand();
await Task.Delay(0, CancellationToken.None);
});
return await rootCommand.InvokeAsync(args);
}
private static void RunCommand()
{
var isValidInput = false;
while (!isValidInput)
{
Console.WriteLine("INPUT: ");
string? input = Console.ReadLine();
if (!string.IsNullOrWhiteSpace(input))
{
isValidInput = true;
}
else
{
Console.WriteLine("Invalid input, please try again...");
}
Console.WriteLine();
}
}
}
If I call GetCancellationToken
, after every Ctrl+C, I get:
If I comment it out, I get:
Seems like a bug to me?
PS: Why is Ctrl+C being treated as input? Shouldn't it by default not do that? I tried Console.TreatControlCAsInput = false;
just in-case but I still got "Invalid input..." before it terminated. I'm on .NET 8.
Thanks!
Metadata
Metadata
Assignees
Labels
No labels