I am looking for an async friendly way to wait for ctrl+c to exit a C# console application. The code below works if I run the compiled binary directly. However, if I run it in the debugger, input ctrl+c, and step through I will hit the closing brace of the program but it does not exit. If I comment out the await, the application finishes normally so I don't think it's a VS settings issue.
using System;
using System.Threading;
using System.Threading.Tasks;
public class Program
{
public static async Task Main()
{
Console.WriteLine("Hello World");
await UntilCancelled().ConfigureAwait(true);
Console.WriteLine("Goodbye Cruel World");
}
/// <summary>
/// Waits until Ctrl+c or Ctrl+Break is entered into the console
/// </summary>
/// <param name="cancellationToken">A passed in cancellation token can also cause the await to complete</param>
/// <returns>True when cancelled</returns>
public static Task UntilCancelled(CancellationToken cancellationToken = default)
{
var cts = new CancellationTokenSource();
//link tokens if caller wants to have ability to cancel for other conditions
if (default != cancellationToken)
cts = CancellationTokenSource.CreateLinkedTokenSource(cts.Token, cancellationToken);
//Attach cancellation to event for exiting the console
Console.CancelKeyPress += (sender, cpe) => cts.Cancel();
var tcs = new TaskCompletionSource<bool>();
cts.Token.Register(s => ((TaskCompletionSource<bool>)s).SetResult(true), tcs);
return tcs.Task;
}
}



