Skip to content

Instantly share code, notes, and snippets.

@AArnott
Last active December 12, 2023 16:33
Show Gist options
  • Star 38 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • 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

I guess not disposed CancellationTokenSource could be a potential memory leak
e.g.

using var _ = CancellationTokenSource; // disposing
CancellationTokenSource.Cancel();
e.Cancel = true;

@AArnott
Copy link
Author

AArnott commented Apr 26, 2023

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.

@asevos
Copy link

asevos commented Sep 2, 2023

Thanks for this gist! Got it on first line when googling c# cancellation token from ctrl c, exactly what I needed

@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