C#C
C#2y ago
92 replies
abdesol

cancellation token to stop Console.ReadLine is only working on the first try

I have the following method I got from stackoverflow
async Task<string?> ReadLineAsync(CancellationToken cancellationToken = default)
{
    var readTask = Task.Run(() => Console.ReadLine());
    await Task.WhenAny(readTask, Task.Delay(-1, cancellationToken));
    cancellationToken.ThrowIfCancellationRequested();
    return await readTask;
}

I run it in a loop while passing it a cancellation token.. and the cancellation token is also in a loop, which means, I recreate it every time.. it works on the first try.. but after the recreation starts for the cancellation token, on
await Task.WhenAny(readTask, Task.Delay(-1, cancellationToken));
cancellation token doesn't get to end first although it should have from the other concurrent task I manage to cancel the token. What could be a possible solution? Thank you!
Was this page helpful?