Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to exit gracefully from a while loop when CancellationTokenSource.Cancel() is used

I have the following program written in dotnet 6:

var cancellationTokenSource = new CancellationTokenSource();

Console.CancelKeyPress += (object? sender, ConsoleCancelEventArgs e) =>
{
    cancellationTokenSource.Cancel();
};

await DoAsync(cancellationTokenSource.Token);

Console.WriteLine("Finished!");

async Task DoAsync(CancellationToken token)
{
    while (!token.IsCancellationRequested)
    {
        Console.WriteLine("Test!");
        await Task.Delay(1000);
    }
}

When I press "Ctrl + C" the program exits with the following error code:
"Program.exe exited with code -1073741510". "Finished!" is never written to the screen.

I cannot understand what exactly happens but it seems that cancellationTokenSource.Cancel() throws an exception and the program finishes with error. As far as I understand, when cancellationTokenSource.Cancel() is called cancellationTokenSource.Token.IsCancellationRequested is set to true and no exception should be thrown.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

What is the reason the applicatiion to finish with exception and how can I gracefully exit the application when the user presses "Ctrl + C"?

I googled a lot but couldn’t find the answer.

>Solution :

Ctrl+C kills the application. As the CancelKeyPress documentation explains, handling the event won’t prevent termination.

To avoid termination you need to set ConsoleCancelEventArgs.Cancel to true

Console.CancelKeyPress += (object? sender, ConsoleCancelEventArgs e) =>
{
    e.Cancel=true;
    cancellationTokenSource.Cancel();
};
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading