Skip to content

Instantly share code, notes, and snippets.

@AArnott
Last active December 12, 2023 16:33
Show Gist options
  • Save AArnott/daa2e450fb5af165f5ca2aff42a4b5cc to your computer and use it in GitHub Desktop.
Save AArnott/daa2e450fb5af165f5ca2aff42a4b5cc to your computer and use it in GitHub Desktop.
Graceful console app cancellation on Ctrl+C
class Program
{
static async Task Main(string[] args)
{
// Add this to your C# console app's Main method to give yourself
// a CancellationToken that is canceled when the user hits Ctrl+C.
var cts = new CancellationTokenSource();
Console.CancelKeyPress += (s, e) =>
{
Console.WriteLine("Canceling...");
cts.Cancel();
e.Cancel = true;
};
await DoSomethingAsync(cts.Token);
}
}
@sunnamed434
Copy link

Meh, CTS won't leak memory unless you create it linked to another, longer-lived CTS. That, and the fact that there is exactly one of these that lasts the whole life of the process, gives you 3 reasons to not care in this particular case. But ya, disposing the CTS is harmless as long as you do it at process exit time.

Well, finally convinced of these words

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment