Looking for a better way to cancel on keypress from the console
I'm using the following code to trigger a cancellation token when the user presses a key. I had to use a thread, because some of these operations are long running, so I can't just check for keypresses between async calls. I feel like there has to be a better way than spawning a thread, but it's just not coming to me.
static void MonitorThreadProc(object state){ var cts = (CancellationTokenSource)state; while(!Console.KeyAvailable) { Thread.Sleep(10); } cts.Cancel();}static async Task<int> Main(string[] args){ if (args.Length < 2) { return -1; } var port = args[0]; var path = args[1]; try { using (var link = new EspLink(port)) { var cts = new CancellationTokenSource(); var mon = new Thread(new ParameterizedThreadStart(MonitorThreadProc)); mon.Start(cts); var tok = cts.Token; Console.WriteLine("Press any key to cancel..."); Console.Write("Connecting..."); await Console.Out.FlushAsync(); await link.ConnectAsync(true, 3, true, tok, link.DefaultTimeout, new EspProgress()); Console.WriteLine("\bdone!"); await Console.Out.FlushAsync(); ... // complete code is here https://pastebin.com/Cpu18pYm mon.Abort(); } return 0; } catch (OperationCanceledException) { Console.WriteLine("Operation canceled by user. Device may be in invalid state."); return 1; }}
static void MonitorThreadProc(object state){ var cts = (CancellationTokenSource)state; while(!Console.KeyAvailable) { Thread.Sleep(10); } cts.Cancel();}static async Task<int> Main(string[] args){ if (args.Length < 2) { return -1; } var port = args[0]; var path = args[1]; try { using (var link = new EspLink(port)) { var cts = new CancellationTokenSource(); var mon = new Thread(new ParameterizedThreadStart(MonitorThreadProc)); mon.Start(cts); var tok = cts.Token; Console.WriteLine("Press any key to cancel..."); Console.Write("Connecting..."); await Console.Out.FlushAsync(); await link.ConnectAsync(true, 3, true, tok, link.DefaultTimeout, new EspProgress()); Console.WriteLine("\bdone!"); await Console.Out.FlushAsync(); ... // complete code is here https://pastebin.com/Cpu18pYm mon.Abort(); } return 0; } catch (OperationCanceledException) { Console.WriteLine("Operation canceled by user. Device may be in invalid state."); return 1; }}