Add ctrl c handler and modify enter key handler to be non-blocking (#155)
authorJohn Salem <josalem@microsoft.com>
Wed, 17 Apr 2019 00:13:29 +0000 (17:13 -0700)
committerGitHub <noreply@github.com>
Wed, 17 Apr 2019 00:13:29 +0000 (17:13 -0700)
* Add  ctrl c handler and modify enter key handler to be non-blocking

src/Tools/dotnet-trace/CommandLine/Commands/CollectCommand.cs

index 9b6d5709994a2f791b72d8decdc0ce9168d227cf..ce5116e520f37e097def8c97b00c678d6aad07c6 100644 (file)
@@ -8,6 +8,7 @@ using System.CommandLine;
 using System.CommandLine.Invocation;
 using System.Diagnostics;
 using System.IO;
+using System.Threading;
 using System.Threading.Tasks;
 
 namespace Microsoft.Diagnostics.Tools.Trace
@@ -35,6 +36,8 @@ namespace Microsoft.Diagnostics.Tools.Trace
                     outputPath: null, // Not used on the streaming scenario.
                     Extensions.ToProviders(providers));
 
+                var shouldExit = new ManualResetEvent(false);
+
                 ulong sessionId = 0;
                 using (Stream stream = EventPipeClient.CollectTracing(processId, configuration, out sessionId))
                 {
@@ -67,8 +70,15 @@ namespace Microsoft.Diagnostics.Tools.Trace
                     });
                     collectingTask.Start();
 
-                    Console.Out.WriteLine("press <Enter> to exit...");
-                    while (Console.ReadKey().Key != ConsoleKey.Enter) { }
+                    Console.Out.WriteLine("press <Enter> or <Ctrl+c> to exit...");
+                    System.Console.CancelKeyPress += (sender, args) => {
+                        args.Cancel = true;
+                        shouldExit.Set();
+                    };
+
+                    do {
+                        while (!Console.KeyAvailable && !shouldExit.WaitOne(250)) { }
+                    } while (!shouldExit.WaitOne(0) && Console.ReadKey(true).Key != ConsoleKey.Enter);
 
                     EventPipeClient.StopTracing(processId, sessionId);
                     collectingTask.Wait();