@@ -68,11 +68,11 @@ public static CommandLineBuilder CancelOnProcessTermination(
6868 ConsoleCancelEventHandler ? consoleHandler = null ;
6969 EventHandler ? processExitHandler = null ;
7070 ManualResetEventSlim ? blockProcessExit = null ;
71+ CancellationTokenSource ? cts = null ;
7172
7273 context . AddLinkedCancellationToken ( ( ) =>
7374 {
74- //TODO: This CancellationTokenSource is never disposed...
75- CancellationTokenSource cts = new ( ) ;
75+ cts = new CancellationTokenSource ( ) ;
7676 blockProcessExit = new ManualResetEventSlim ( initialState : false ) ;
7777 processExitHandler = ( _ , _ ) =>
7878 {
@@ -102,7 +102,6 @@ public static CommandLineBuilder CancelOnProcessTermination(
102102 // https://docs.microsoft.com/en-us/dotnet/api/system.appdomain.processexit?view=net-6.0
103103 consoleHandler = ( _ , args ) =>
104104 {
105- cts . Cancel ( ) ;
106105 // Stop the process from terminating.
107106 // Since the context was cancelled, the invocation should
108107 // finish and Main will return.
@@ -125,15 +124,14 @@ public static CommandLineBuilder CancelOnProcessTermination(
125124 // Cancel synchronously here - no need to perform it asynchronously as the timeout is already running (and would kill the process if needed),
126125 // plus we cannot wait only on the cancellation (e.g. via `Task.Factory.StartNew(cts.Cancel).Wait(cancelationProcessingTimeout.Value)`)
127126 // as we need to abort any other possible execution within the process - even outside the context of cancellation processing
128- cts . Cancel ( ) ;
127+ cts ? . Cancel ( ) ;
129128 } ;
130129 Console . CancelKeyPress += consoleHandler ;
131130 AppDomain . CurrentDomain . ProcessExit += processExitHandler ;
132131
133132 return cts . Token ;
134133 } ) ;
135134
136-
137135 try
138136 {
139137 await next ( context ) ;
@@ -142,6 +140,7 @@ public static CommandLineBuilder CancelOnProcessTermination(
142140 {
143141 Console . CancelKeyPress -= consoleHandler ;
144142 AppDomain . CurrentDomain . ProcessExit -= processExitHandler ;
143+ Interlocked . Exchange ( ref cts , null ) ? . Dispose ( ) ;
145144 blockProcessExit ? . Set ( ) ;
146145 }
147146 } , MiddlewareOrderInternal . Startup ) ;
0 commit comments