1
1
// Copyright (c) Microsoft Corporation. All rights reserved.
2
2
// Licensed under the MIT license.
3
3
4
+ using System ;
4
5
using System . CommandLine ;
5
- using System . CommandLine . Builder ;
6
- using System . CommandLine . Hosting ;
7
6
using System . CommandLine . Parsing ;
8
-
7
+ using System . Diagnostics ;
9
8
using System . IO ;
9
+ using System . Threading ;
10
10
using System . Threading . Tasks ;
11
- using Microsoft . Extensions . Configuration ;
12
- using Microsoft . Extensions . Hosting ;
13
11
using Microsoft . Extensions . Logging ;
14
12
using Microsoft . OpenApi . Hidi . Handlers ;
15
13
@@ -19,6 +17,9 @@ static class Program
19
17
{
20
18
static async Task Main ( string [ ] args )
21
19
{
20
+ // subscribe to CancelKeyPress event to listen for termination requests from users through Ctrl+C or Ctrl+Break keys
21
+ Console . CancelKeyPress += new ConsoleCancelEventHandler ( Console_CancelKeyPressEvent ) ;
22
+
22
23
var rootCommand = new RootCommand ( ) {
23
24
} ;
24
25
@@ -127,5 +128,29 @@ static async Task Main(string[] args)
127
128
//// Wait for logger to write messages to the console before exiting
128
129
await Task . Delay ( 10 ) ;
129
130
}
131
+
132
+ /// <summary>
133
+ /// This event is raised when the user presses either of the two breaking key combinations: Ctrl+C or Ctrl+Break keys.
134
+ /// </summary>
135
+ /// <param name="sender"></param>
136
+ /// <param name="eventArgs"></param>
137
+ private static void Console_CancelKeyPressEvent ( object sender , ConsoleCancelEventArgs eventArgs )
138
+ {
139
+ if ( ( eventArgs . SpecialKey == ConsoleSpecialKey . ControlC ) || ( eventArgs . SpecialKey == ConsoleSpecialKey . ControlBreak ) )
140
+ {
141
+ Console . WriteLine ( "CTRL+C pressed, aborting current process..." ) ;
142
+ Thread . Sleep ( 5000 ) ;
143
+
144
+ if ( Process . GetCurrentProcess ( ) . HasExited )
145
+ {
146
+ Console . WriteLine ( "Process has already exited." ) ;
147
+ }
148
+ else
149
+ {
150
+ Console . WriteLine ( "Process has not exited, attempting to kill process..." ) ;
151
+ Process . GetCurrentProcess ( ) . Kill ( ) ;
152
+ }
153
+ }
154
+ }
130
155
}
131
156
}
0 commit comments