Skip to content

Commit 45dd6eb

Browse files
committed
Handling TODO, to dispose of CancellationTokenSource
1 parent a0eb9c8 commit 45dd6eb

File tree

1 file changed

+4
-5
lines changed

1 file changed

+4
-5
lines changed

src/System.CommandLine/Builder/CommandLineBuilderExtensions.cs

Lines changed: 4 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -67,11 +67,11 @@ public static CommandLineBuilder CancelOnProcessTermination(
6767
ConsoleCancelEventHandler? consoleHandler = null;
6868
EventHandler? processExitHandler = null;
6969
ManualResetEventSlim? blockProcessExit = null;
70+
CancellationTokenSource? cts = null;
7071

7172
context.AddLinkedCancellationToken(() =>
7273
{
73-
//TODO: This CancellationTokenSource is never disposed...
74-
CancellationTokenSource cts = new();
74+
cts = new CancellationTokenSource();
7575
blockProcessExit = new ManualResetEventSlim(initialState: false);
7676
processExitHandler = (_, _) =>
7777
{
@@ -101,7 +101,6 @@ public static CommandLineBuilder CancelOnProcessTermination(
101101
// https://docs.microsoft.com/en-us/dotnet/api/system.appdomain.processexit?view=net-6.0
102102
consoleHandler = (_, args) =>
103103
{
104-
cts.Cancel();
105104
// Stop the process from terminating.
106105
// Since the context was cancelled, the invocation should
107106
// finish and Main will return.
@@ -124,15 +123,14 @@ public static CommandLineBuilder CancelOnProcessTermination(
124123
// Cancel synchronously here - no need to perform it asynchronously as the timeout is already running (and would kill the process if needed),
125124
// plus we cannot wait only on the cancellation (e.g. via `Task.Factory.StartNew(cts.Cancel).Wait(cancelationProcessingTimeout.Value)`)
126125
// as we need to abort any other possible execution within the process - even outside the context of cancellation processing
127-
cts.Cancel();
126+
cts?.Cancel();
128127
};
129128
Console.CancelKeyPress += consoleHandler;
130129
AppDomain.CurrentDomain.ProcessExit += processExitHandler;
131130

132131
return cts.Token;
133132
});
134133

135-
136134
try
137135
{
138136
await next(context);
@@ -141,6 +139,7 @@ public static CommandLineBuilder CancelOnProcessTermination(
141139
{
142140
Console.CancelKeyPress -= consoleHandler;
143141
AppDomain.CurrentDomain.ProcessExit -= processExitHandler;
142+
Interlocked.Exchange(ref cts, null)?.Dispose();
144143
blockProcessExit?.Set();
145144
}
146145
}, MiddlewareOrderInternal.Startup);

0 commit comments

Comments
 (0)