diff --git a/src/Cli/AGENTS.md b/src/Cli/AGENTS.md
index fe6969097a38..8beaf31170ef 100644
--- a/src/Cli/AGENTS.md
+++ b/src/Cli/AGENTS.md
@@ -20,6 +20,63 @@ MSBuild emits final telemetry after `BuildFinished`. `Shutdown` completes one lo
instance. It does not necessarily end the process. Refresh the environment and trace
context for each persistent-server request.
+Managed and Native AOT command execution use
+`Microsoft.DotNet.Cli.Utils/ProcessLifecycle.cs` as the shared owner of Ctrl+C,
+SIGTERM, and process-exit cancellation. The managed entry point initializes it for the
+process lifetime; the Native AOT entry point initializes it only while handling a command
+in-process and unregisters it before managed fallback. Merely launching a child through
+`ProcessReaper.cs` must not initialize CLI lifecycle handling in library hosts.
+
+Pass the lifecycle token through System.CommandLine invocation and command operations.
+Process-launch and forwarding helpers must require callers to supply a cancellation
+token; do not add tokenless overloads or optional cancellation-token parameters.
+The first Ctrl+C requests cooperative cancellation and permits 200 milliseconds for
+cleanup; expiration of that deadline requests forceful cancellation, gives observers a
+bounded window to terminate and reap child processes, and then exits with the
+signal-derived exit code. A second Ctrl+C or SIGTERM exits immediately. Transaction
+rollback and other critical operations may use `OverrideSoftCancellationTimeout` to
+extend or suspend
+the automatic deadline, but the override must never suppress an explicit forceful signal.
+Child processes observe cooperative signals directly and are killed only when forceful
+cancellation is requested. While a lifecycle-managed external process is running,
+`Command` suspends the automatic soft-cancellation deadline so the child can finish
+gracefully; a second Ctrl+C or SIGTERM still forces termination. System.CommandLine may
+wrap the lifecycle token before it reaches a command action, so process termination must
+use lifecycle initialization state rather than token identity to distinguish lifecycle
+cancellation from standalone library callers. On Unix, forward SIGTERM to the child
+before bounded forceful termination.
+`ProcessReaper.cs` owns child-process signal forwarding and cleanup; do not add a
+competing command-line termination handler for those signals. MSBuild operations use a
+two-second soft-cancellation override so submissions and loggers, including binary
+loggers, can finish cancellation cleanup; a second Ctrl+C or SIGTERM still bypasses it.
+MTP test execution suspends the automatic deadline while running test applications so
+their own first-Ctrl+C handlers can report final results. Its cancellation manager must
+observe the shared cooperative and forceful lifecycle tokens: cooperative cancellation
+stops queueing new applications, while forceful cancellation kills all registered test
+application process trees before the lifecycle exits.
+
+### Cancellation and cleanup
+
+Forward-operation cancellation must not prevent transaction rollback. MSI manifest and
+pack rollback create a distinct cancellation scope inside each rollback callback, never
+linked to the cancelled forward token; keep the original cancellation exception after
+cleanup. The deterministic installer seams are exercised by
+[`GivenMsiCancellation`](../../test/dotnet.Tests/CommandTests/Workload/Install/GivenMsiCancellation.cs).
+Only roll back MSIs whose installation this transaction actually attempted; mark the
+attempt before native execution so partial installs still roll back, but cancellation
+before installation and already-installed no-ops cannot remove existing manifests.
+
+`Console.In` synchronizes `ReadLineAsync` as well as `ReadLine`. The
+[`run-api` command](dotnet/Commands/Run/Api/RunApiCommand.cs) uses
+`Console.OpenStandardInputHandle()` with `FileStream`/`StreamReader` instead. Keep the
+cancellable wait: Unix file I/O cannot interrupt an already blocked read, so at most one
+runtime worker can remain until process exit. Keep its regression out of process with a
+real open stdin pipe; see
+[`RunApiCancellationTests`](../../test/dotnet.Tests/CommandTests/Run/RunApiCancellationTests.cs).
+On Linux, its helper waits for `/proc/self/task/*/syscall` to report a blocked
+`read(0, ...)` before cancelling; an incomplete task alone does not establish that the
+runtime worker has started the read.
+
## Three-project command split
A `dotnet` command or option spans three cooperating projects:
diff --git a/src/Cli/Microsoft.DotNet.Cli.CommandLine/CommandExtensions.cs b/src/Cli/Microsoft.DotNet.Cli.CommandLine/CommandExtensions.cs
new file mode 100644
index 000000000000..6bb1c7680932
--- /dev/null
+++ b/src/Cli/Microsoft.DotNet.Cli.CommandLine/CommandExtensions.cs
@@ -0,0 +1,28 @@
+// Licensed to the .NET Foundation under one or more agreements.
+// The .NET Foundation licenses this file to you under the MIT license.
+
+using System.CommandLine;
+
+namespace Microsoft.DotNet.Cli.CommandLine;
+
+///
+/// Extensions that make it easy to wire up cancellable command actions without requiring
+/// every command handler in the CLI to be written against the asynchronous System.CommandLine
+/// APIs. The synchronous still receives the
+/// that System.CommandLine produces (for example when a Ctrl+C/SIGTERM is observed), so that it
+/// can be checked or forwarded to cancellable APIs as appropriate.
+///
+public static class CommandExtensions
+{
+ extension(Command command)
+ {
+ ///
+ /// Sets the action for the command to a synchronous delegate that accepts the
+ /// supplied by System.CommandLine's invocation pipeline.
+ ///
+ public void SetAction(Func action)
+ {
+ command.SetAction((parseResult, cancellationToken) => Task.FromResult(action(parseResult, cancellationToken)));
+ }
+ }
+}
diff --git a/src/Cli/Microsoft.DotNet.Cli.Utils/BuiltInCommand.cs b/src/Cli/Microsoft.DotNet.Cli.Utils/BuiltInCommand.cs
index d8fb130f272f..fda4d06f02fd 100644
--- a/src/Cli/Microsoft.DotNet.Cli.Utils/BuiltInCommand.cs
+++ b/src/Cli/Microsoft.DotNet.Cli.Utils/BuiltInCommand.cs
@@ -34,8 +34,10 @@ internal BuiltInCommand(string commandName, IEnumerable commandArgs, Fun
_stdErr = new StreamForwarder();
}
- public CommandResult Execute()
+ public CommandResult Execute(CancellationToken cancellationToken)
{
+ cancellationToken.ThrowIfCancellationRequested();
+
TextWriter originalConsoleOut = _environment.GetConsoleOut();
TextWriter originalConsoleError = _environment.GetConsoleError();
string originalWorkingDirectory = _environment.GetWorkingDirectory();
diff --git a/src/Cli/Microsoft.DotNet.Cli.Utils/Command.cs b/src/Cli/Microsoft.DotNet.Cli.Utils/Command.cs
index 0624738a66c0..0c3764760f7c 100644
--- a/src/Cli/Microsoft.DotNet.Cli.Utils/Command.cs
+++ b/src/Cli/Microsoft.DotNet.Cli.Utils/Command.cs
@@ -21,16 +21,45 @@ public class Command(Process? process, bool trimTrailingNewlines = false, IDicti
private readonly bool _trimTrailingNewlines = trimTrailingNewlines;
- public CommandResult Execute()
+ private bool _logProcess = true;
+
+ private bool _suspendSoftCancellationTimeout = true;
+
+ public CommandResult Execute(CancellationToken cancellationToken)
+ {
+ cancellationToken.ThrowIfCancellationRequested();
+ return ExecuteCore(processStarted: null, cancellationToken);
+ }
+
+ public CommandResult Execute(Action? processStarted, CancellationToken cancellationToken)
{
- return Execute(null);
+ cancellationToken.ThrowIfCancellationRequested();
+ return ExecuteCore(processStarted, cancellationToken);
}
- public CommandResult Execute(Action? processStarted)
+
+ internal Command WithoutProcessLogging()
{
- Reporter.Verbose.WriteLine(string.Format(
- LocalizableStrings.RunningFileNameArguments,
- _process.StartInfo.FileName,
- _process.StartInfo.Arguments));
+ ThrowIfRunning();
+ _logProcess = false;
+ return this;
+ }
+
+ internal Command WithoutSoftCancellationTimeoutOverride()
+ {
+ ThrowIfRunning();
+ _suspendSoftCancellationTimeout = false;
+ return this;
+ }
+
+ private CommandResult ExecuteCore(Action? processStarted, CancellationToken cancellationToken)
+ {
+ if (_logProcess)
+ {
+ Reporter.Verbose.WriteLine(string.Format(
+ LocalizableStrings.RunningFileNameArguments,
+ _process.StartInfo.FileName,
+ _process.StartInfo.Arguments));
+ }
ThrowIfRunning();
@@ -39,7 +68,7 @@ public CommandResult Execute(Action? processStarted)
_process.EnableRaisingEvents = true;
Stopwatch? sw = null;
- if (CommandLoggingContext.IsVerbose)
+ if (_logProcess && CommandLoggingContext.IsVerbose)
{
sw = Stopwatch.StartNew();
@@ -47,18 +76,48 @@ public CommandResult Execute(Action? processStarted)
}
using (var reaper = ProcessReaper.Create(_process))
+ using (ProcessLifecycle.IsInitialized && _suspendSoftCancellationTimeout
+ ? ProcessLifecycle.OverrideSoftCancellationTimeout(Timeout.InfiniteTimeSpan)
+ : null)
{
_process.Start();
processStarted?.Invoke(_process);
reaper.NotifyProcessStarted();
- Reporter.Verbose.WriteLine(string.Format(
- LocalizableStrings.ProcessId,
- _process.Id));
+ if (_logProcess)
+ {
+ Reporter.Verbose.WriteLine(string.Format(
+ LocalizableStrings.ProcessId,
+ _process.Id));
+ }
var taskOut = _stdOut?.BeginRead(_process.StandardOutput);
var taskErr = _stdErr?.BeginRead(_process.StandardError);
- _process.WaitForExit();
+
+ CancellationToken processTerminationToken =
+ ProcessLifecycle.GetProcessTerminationToken(cancellationToken);
+ if (!processTerminationToken.CanBeCanceled)
+ {
+ _process.WaitForExit();
+ }
+ else
+ {
+ bool cancellationWon = false;
+ while (!_process.WaitForExit(milliseconds: 100))
+ {
+ if (processTerminationToken.IsCancellationRequested)
+ {
+ cancellationWon = true;
+ TerminateProcess(reaper, _process);
+ break;
+ }
+ }
+
+ if (cancellationWon)
+ {
+ cancellationToken.ThrowIfCancellationRequested();
+ }
+ }
taskOut?.Wait();
taskErr?.Wait();
@@ -66,7 +125,7 @@ public CommandResult Execute(Action? processStarted)
var exitCode = _process.ExitCode;
- if (CommandLoggingContext.IsVerbose)
+ if (_logProcess && CommandLoggingContext.IsVerbose)
{
Debug.Assert(sw is not null);
var message = string.Format(
@@ -91,6 +150,24 @@ public CommandResult Execute(Action? processStarted)
_stdErr?.CapturedOutput);
}
+ private static void TerminateProcess(ProcessReaper reaper, Process process)
+ {
+ try
+ {
+ reaper.TerminateProcess();
+ }
+ catch (InvalidOperationException) when (process.HasExited)
+ {
+ // The process exited before termination reached it.
+ }
+ catch (System.ComponentModel.Win32Exception) when (process.HasExited)
+ {
+ // The process exited while its process tree was being enumerated.
+ }
+
+ process.WaitForExit();
+ }
+
public ICommand WorkingDirectory(string? projectDirectory)
{
_process.StartInfo.WorkingDirectory = projectDirectory;
diff --git a/src/Cli/Microsoft.DotNet.Cli.Utils/ExponentialRetry.cs b/src/Cli/Microsoft.DotNet.Cli.Utils/ExponentialRetry.cs
index d3631c1a6346..50043d7fa8b5 100644
--- a/src/Cli/Microsoft.DotNet.Cli.Utils/ExponentialRetry.cs
+++ b/src/Cli/Microsoft.DotNet.Cli.Utils/ExponentialRetry.cs
@@ -69,15 +69,16 @@ public static async Task ExecuteWithRetry(Func action,
}
public static async Task ExecuteWithRetryOnFailure(Func> action,
+ CancellationToken cancellationToken,
int maxRetryCount = 3,
Func>? timer = null)
{
- timer = timer ?? (() => Timer(Intervals));
+ timer ??= () => Timer(Intervals, cancellationToken);
return await ExecuteAsyncWithRetry(action, result => result != null && !result.Equals(default), maxRetryCount, timer);
}
- public static IEnumerable Timer(IEnumerable interval)
+ public static IEnumerable Timer(IEnumerable interval, CancellationToken cancellationToken)
{
- return interval.Select(Task.Delay);
+ return interval.Select(delay => Task.Delay(delay, cancellationToken));
}
}
diff --git a/src/Cli/Microsoft.DotNet.Cli.Utils/Extensions/LockFileFormatExtensions.cs b/src/Cli/Microsoft.DotNet.Cli.Utils/Extensions/LockFileFormatExtensions.cs
index eec603000473..68702339a60d 100644
--- a/src/Cli/Microsoft.DotNet.Cli.Utils/Extensions/LockFileFormatExtensions.cs
+++ b/src/Cli/Microsoft.DotNet.Cli.Utils/Extensions/LockFileFormatExtensions.cs
@@ -8,7 +8,10 @@ namespace Microsoft.DotNet.Cli.Utils.Extensions;
public static class LockFileFormatExtensions
{
- public static async Task ReadWithLock(this LockFileFormat subject, string path)
+ public static async Task ReadWithLock(
+ this LockFileFormat subject,
+ string path,
+ CancellationToken cancellationToken)
{
return await ConcurrencyUtilities.ExecuteWithFileLockedAsync(
path,
@@ -26,6 +29,6 @@ public static async Task ReadWithLock(this LockFileFormat subject, str
return lockFile;
},
- CancellationToken.None);
+ cancellationToken);
}
}
diff --git a/src/Cli/Microsoft.DotNet.Cli.Utils/Extensions/ProcessStartInfoExtensions.cs b/src/Cli/Microsoft.DotNet.Cli.Utils/Extensions/ProcessStartInfoExtensions.cs
index 46198b39b803..de03e41cdc4f 100644
--- a/src/Cli/Microsoft.DotNet.Cli.Utils/Extensions/ProcessStartInfoExtensions.cs
+++ b/src/Cli/Microsoft.DotNet.Cli.Utils/Extensions/ProcessStartInfoExtensions.cs
@@ -7,56 +7,49 @@ namespace Microsoft.DotNet.Cli.Utils.Extensions;
internal static class ProcessStartInfoExtensions
{
- public static int Execute(this ProcessStartInfo startInfo)
+ public static int Execute(this ProcessStartInfo startInfo, CancellationToken cancellationToken)
+ => Execute(startInfo, suspendSoftCancellationTimeout: true, cancellationToken);
+
+ internal static int Execute(
+ this ProcessStartInfo startInfo,
+ bool suspendSoftCancellationTimeout,
+ CancellationToken cancellationToken)
{
ArgumentNullException.ThrowIfNull(startInfo);
- var process = new Process
+ using var process = new Process
{
StartInfo = startInfo
};
- using (var reaper = ProcessReaper.Create(process))
+ Command command = new Command(process).WithoutProcessLogging();
+ if (!suspendSoftCancellationTimeout)
{
- process.Start();
- reaper.NotifyProcessStarted();
- process.WaitForExit();
+ command.WithoutSoftCancellationTimeoutOverride();
}
- return process.ExitCode;
+ return command.Execute(cancellationToken).ExitCode;
}
- public static int ExecuteAndCaptureOutput(this ProcessStartInfo startInfo, out string? stdOut, out string? stdErr)
+ public static int ExecuteAndCaptureOutput(
+ this ProcessStartInfo startInfo,
+ out string? stdOut,
+ out string? stdErr,
+ CancellationToken cancellationToken)
{
- var outStream = new StreamForwarder().Capture();
- var errStream = new StreamForwarder().Capture();
-
- startInfo.RedirectStandardOutput = true;
- startInfo.RedirectStandardError = true;
-
- var process = new Process
+ using var process = new Process
{
- StartInfo = startInfo,
- EnableRaisingEvents = true
+ StartInfo = startInfo
};
- using (var reaper = ProcessReaper.Create(process))
- {
- process.Start();
- reaper.NotifyProcessStarted();
-
- var taskOut = outStream.BeginRead(process.StandardOutput);
- var taskErr = errStream.BeginRead(process.StandardError);
-
- process.WaitForExit();
-
- taskOut.Wait();
- taskErr.Wait();
-
- stdOut = outStream.CapturedOutput;
- stdErr = errStream.CapturedOutput;
- }
+ CommandResult result = new Command(process)
+ .WithoutProcessLogging()
+ .CaptureStdOut()
+ .CaptureStdErr()
+ .Execute(cancellationToken);
- return process.ExitCode;
+ stdOut = result.StdOut;
+ stdErr = result.StdErr;
+ return result.ExitCode;
}
}
diff --git a/src/Cli/Microsoft.DotNet.Cli.Utils/ForwardingAppImplementation.cs b/src/Cli/Microsoft.DotNet.Cli.Utils/ForwardingAppImplementation.cs
index 1b2058d17744..baa8b7f099dd 100644
--- a/src/Cli/Microsoft.DotNet.Cli.Utils/ForwardingAppImplementation.cs
+++ b/src/Cli/Microsoft.DotNet.Cli.Utils/ForwardingAppImplementation.cs
@@ -64,9 +64,9 @@ public ForwardingAppImplementation(
_allArgs = allArgs.ToArray();
}
- public int Execute()
+ public int Execute(CancellationToken cancellationToken)
{
- return GetProcessStartInfo().Execute();
+ return GetProcessStartInfo().Execute(cancellationToken);
}
public ProcessStartInfo GetProcessStartInfo()
diff --git a/src/Cli/Microsoft.DotNet.Cli.Utils/ICommand.cs b/src/Cli/Microsoft.DotNet.Cli.Utils/ICommand.cs
index 6e9856a5297a..e268f8635042 100644
--- a/src/Cli/Microsoft.DotNet.Cli.Utils/ICommand.cs
+++ b/src/Cli/Microsoft.DotNet.Cli.Utils/ICommand.cs
@@ -5,7 +5,7 @@ namespace Microsoft.DotNet.Cli.Utils;
public interface ICommand
{
- CommandResult Execute();
+ CommandResult Execute(CancellationToken cancellationToken);
ICommand WorkingDirectory(string projectDirectory);
diff --git a/src/Cli/Microsoft.DotNet.Cli.Utils/MSBuildForwardingAppWithoutLogging.cs b/src/Cli/Microsoft.DotNet.Cli.Utils/MSBuildForwardingAppWithoutLogging.cs
index f484fc5fb715..c8a11194230a 100644
--- a/src/Cli/Microsoft.DotNet.Cli.Utils/MSBuildForwardingAppWithoutLogging.cs
+++ b/src/Cli/Microsoft.DotNet.Cli.Utils/MSBuildForwardingAppWithoutLogging.cs
@@ -180,13 +180,19 @@ public void EnvironmentVariable(string name, string? value)
///
/// Run the MSBuild arguments that have been previously specified.
///
- public int Execute() => Execute(workingDirectory: null);
+ public int Execute(CancellationToken cancellationToken) => Execute(workingDirectory: null, cancellationToken);
- ///
+ ///
///
/// When specified, run out-of-process in this directory without changing the caller's directory.
///
- public int Execute(string? workingDirectory)
+ public int Execute(string? workingDirectory, CancellationToken cancellationToken)
+ => Execute(workingDirectory, suspendSoftCancellationTimeout: true, cancellationToken);
+
+ internal int Execute(
+ string? workingDirectory,
+ bool suspendSoftCancellationTimeout,
+ CancellationToken cancellationToken)
{
if (workingDirectory is not null && _forwardingApp is null)
{
@@ -201,13 +207,13 @@ public int Execute(string? workingDirectory)
startInfo.WorkingDirectory = workingDirectory;
}
- return startInfo.Execute();
+ return startInfo.Execute(suspendSoftCancellationTimeout, cancellationToken);
}
else
{
if (RuntimeFeature.IsDynamicCodeSupported)
{
- return ExecuteInProc(GetAllArguments());
+ return ExecuteInProc(GetAllArguments(), cancellationToken);
}
else
{
@@ -222,15 +228,20 @@ public int Execute(string? workingDirectory)
/// After execution, the original environment variables are restored for any remaining cleanup work the dotnet CLI needs to perform.
///
[RequiresDynamicCode("Calls MSBuildApp.Main, which is not AOT-safe")]
- public int ExecuteInProc(string[] arguments)
+ public int ExecuteInProc(string[] arguments, CancellationToken cancellationToken)
{
+ cancellationToken.ThrowIfCancellationRequested();
+
using var _ = SetEnvironmentVariables(_msbuildRequiredEnvironmentVariables);
+ using CancellationTokenRegistration cancellationRegistration = cancellationToken.Register(
+ static () => Build.Execution.BuildManager.DefaultBuildManager.CancelAllSubmissions());
+
try
{
// Execute MSBuild in the current process by calling its Main method.
return Build.CommandLine.MSBuildApp.Main(arguments);
}
- catch (Exception exception)
+ catch (Exception exception) when (exception is not OperationCanceledException)
{
// MSBuild, like all well-behaved CLI tools, handles all exceptions. In the unlikely case
// that something still escapes, we print the exception and fail the call. Non-localized
diff --git a/src/Cli/Microsoft.DotNet.Cli.Utils/NativeMethods.txt b/src/Cli/Microsoft.DotNet.Cli.Utils/NativeMethods.txt
index 634b3b0f4554..761a5121f6f1 100644
--- a/src/Cli/Microsoft.DotNet.Cli.Utils/NativeMethods.txt
+++ b/src/Cli/Microsoft.DotNet.Cli.Utils/NativeMethods.txt
@@ -37,6 +37,7 @@ SafeArrayUnlock
SendMessageTimeout
SetInformationJobObject
SetConsoleCtrlHandler
+TerminateJobObject
WinVerifyTrust
// Interfaces
diff --git a/src/Cli/Microsoft.DotNet.Cli.Utils/ProcessLifecycle.cs b/src/Cli/Microsoft.DotNet.Cli.Utils/ProcessLifecycle.cs
new file mode 100644
index 000000000000..eea4a40c4704
--- /dev/null
+++ b/src/Cli/Microsoft.DotNet.Cli.Utils/ProcessLifecycle.cs
@@ -0,0 +1,304 @@
+// Licensed to the .NET Foundation under one or more agreements.
+// The .NET Foundation licenses this file to you under the MIT license.
+
+namespace Microsoft.DotNet.Cli.Utils;
+
+internal static class ProcessLifecycle
+{
+ private const int SigIntExitCode = 130;
+ private const int SigTermExitCode = 143;
+ private static readonly TimeSpan s_defaultSoftCancellationTimeout = TimeSpan.FromMilliseconds(200);
+ private static readonly TimeSpan s_forcefulExitFallbackTimeout = TimeSpan.FromMilliseconds(500);
+ private static readonly object s_lock = new();
+ private static readonly CancellationTokenSource s_cancellationTokenSource = new();
+ private static readonly CancellationTokenSource s_forcefulCancellationTokenSource = new();
+ private static readonly Dictionary s_softCancellationTimeoutOverrides = [];
+#if NET
+ private static PosixSignalRegistration? s_sigTermRegistration;
+#endif
+ private static Timer? s_forcefulCancellationTimer;
+ private static Timer? s_forcefulExitTimer;
+ private static int s_initializationCount;
+ private static int s_nextTimeoutOverrideId;
+ private static int s_forcefulCancellationTimerVersion;
+ private static int s_cancellationRequested;
+ private static int s_forcefulCancellationRequested;
+ private static int s_signalExitCode;
+
+ public static CancellationToken CancellationToken => s_cancellationTokenSource.Token;
+
+ internal static CancellationToken ForcefulCancellationToken => s_forcefulCancellationTokenSource.Token;
+
+ internal static bool IsSignalTerminationRequested => Volatile.Read(ref s_signalExitCode) != 0;
+
+ internal static bool IsSigTermRequested => Volatile.Read(ref s_signalExitCode) == SigTermExitCode;
+
+ internal static bool IsForcefulCancellationRequested => Volatile.Read(ref s_forcefulCancellationRequested) != 0;
+
+ internal static bool IsInitialized => Volatile.Read(ref s_initializationCount) != 0;
+
+ internal static IDisposable Initialize()
+ {
+ lock (s_lock)
+ {
+ if (s_initializationCount++ == 0)
+ {
+ Console.CancelKeyPress += HandleCancelKeyPress;
+ AppDomain.CurrentDomain.ProcessExit += HandleProcessExit;
+#if NET
+ s_sigTermRegistration = PosixSignalRegistration.Create(PosixSignal.SIGTERM, HandleSigTerm);
+#endif
+ }
+ }
+
+ return new Initialization();
+ }
+
+ internal static IDisposable OverrideSoftCancellationTimeout(TimeSpan timeout)
+ {
+ if (timeout < TimeSpan.Zero && timeout != Timeout.InfiniteTimeSpan)
+ {
+ throw new ArgumentOutOfRangeException(nameof(timeout));
+ }
+
+ lock (s_lock)
+ {
+ int id = ++s_nextTimeoutOverrideId;
+ s_softCancellationTimeoutOverrides.Add(id, timeout);
+ ScheduleForcefulCancellation_NoLock();
+ return new SoftCancellationTimeoutOverride(id);
+ }
+ }
+
+ internal static CancellationToken GetProcessTerminationToken(CancellationToken cancellationToken)
+ // System.CommandLine links the invocation token before passing it to command
+ // actions, so lifecycle-originated tokens do not retain identity here.
+ => IsInitialized
+ ? s_forcefulCancellationTokenSource.Token
+ : cancellationToken;
+
+ internal static bool TryGetSignalExitCode(CancellationToken cancellationToken, out int exitCode)
+ {
+ exitCode = Volatile.Read(ref s_signalExitCode);
+ return cancellationToken == s_cancellationTokenSource.Token && exitCode != 0;
+ }
+
+ private static void HandleCancelKeyPress(object? sender, ConsoleCancelEventArgs eventArgs)
+ {
+ eventArgs.Cancel = true;
+
+ if (!RequestSoftCancellation(SigIntExitCode))
+ {
+ RequestForcefulCancellation(SigIntExitCode, terminateProcess: true);
+ }
+ }
+
+#if NET
+ private static void HandleSigTerm(PosixSignalContext context)
+ {
+ context.Cancel = true;
+ RequestForcefulCancellation(SigTermExitCode, terminateProcess: true);
+ }
+#endif
+
+ private static void HandleProcessExit(object? sender, EventArgs eventArgs)
+ {
+ bool cancel;
+ lock (s_lock)
+ {
+ cancel = s_cancellationRequested == 0;
+ s_cancellationRequested = 1;
+ }
+
+ if (cancel)
+ {
+ s_cancellationTokenSource.Cancel();
+ }
+ }
+
+ private static bool RequestSoftCancellation(int exitCode)
+ {
+ lock (s_lock)
+ {
+ if (s_cancellationRequested != 0)
+ {
+ return false;
+ }
+
+ s_cancellationRequested = 1;
+ s_signalExitCode = exitCode;
+ ScheduleForcefulCancellation_NoLock();
+ }
+
+ s_cancellationTokenSource.Cancel();
+ return true;
+ }
+
+ private static void RequestForcefulCancellation(int exitCode, bool terminateProcess)
+ {
+ bool cancel = false;
+ bool exitImmediately = false;
+ lock (s_lock)
+ {
+ if (s_forcefulCancellationRequested != 0)
+ {
+ if (terminateProcess)
+ {
+ s_signalExitCode = exitCode;
+ exitImmediately = true;
+ }
+ }
+ else
+ {
+ s_cancellationRequested = 1;
+ s_forcefulCancellationRequested = 1;
+ s_signalExitCode = exitCode;
+ CancelForcefulCancellationTimer_NoLock();
+ cancel = true;
+ }
+ }
+
+ if (exitImmediately)
+ {
+ Environment.Exit(exitCode);
+ }
+
+ if (cancel)
+ {
+ try
+ {
+ s_forcefulCancellationTokenSource.Cancel();
+ if (!terminateProcess)
+ {
+ s_cancellationTokenSource.Cancel();
+ }
+ }
+ finally
+ {
+ if (terminateProcess)
+ {
+ Environment.Exit(exitCode);
+ }
+ }
+ }
+ }
+
+ private static void ScheduleForcefulCancellation_NoLock()
+ {
+ if (s_cancellationRequested == 0 || s_forcefulCancellationRequested != 0 || s_signalExitCode == 0)
+ {
+ return;
+ }
+
+ TimeSpan timeout = s_defaultSoftCancellationTimeout;
+ foreach (TimeSpan timeoutOverride in s_softCancellationTimeoutOverrides.Values)
+ {
+ if (timeoutOverride == Timeout.InfiniteTimeSpan)
+ {
+ timeout = Timeout.InfiniteTimeSpan;
+ break;
+ }
+
+ if (timeoutOverride > timeout)
+ {
+ timeout = timeoutOverride;
+ }
+ }
+
+ CancelForcefulCancellationTimer_NoLock();
+ if (timeout != Timeout.InfiniteTimeSpan)
+ {
+ int version = s_forcefulCancellationTimerVersion;
+ s_forcefulCancellationTimer = new Timer(
+ static state => ForceAfterSoftCancellationTimeout((int)state!),
+ version,
+ timeout,
+ Timeout.InfiniteTimeSpan);
+ }
+ }
+
+ private static void ForceAfterSoftCancellationTimeout(int version)
+ {
+ int exitCode;
+ lock (s_lock)
+ {
+ if (version != s_forcefulCancellationTimerVersion ||
+ s_forcefulCancellationRequested != 0 ||
+ s_signalExitCode == 0)
+ {
+ return;
+ }
+
+ s_forcefulCancellationRequested = 1;
+ exitCode = s_signalExitCode;
+ CancelForcefulCancellationTimer_NoLock();
+ // Give forceful-token observers a bounded chance to terminate and reap child processes.
+ s_forcefulExitTimer = new Timer(
+ static state => Environment.Exit((int)state!),
+ exitCode,
+ s_forcefulExitFallbackTimeout,
+ Timeout.InfiniteTimeSpan);
+ }
+
+ try
+ {
+ s_forcefulCancellationTokenSource.Cancel();
+ }
+ catch (AggregateException)
+ {
+ Environment.Exit(exitCode);
+ }
+ }
+
+ private static void CancelForcefulCancellationTimer_NoLock()
+ {
+ s_forcefulCancellationTimerVersion++;
+ s_forcefulCancellationTimer?.Dispose();
+ s_forcefulCancellationTimer = null;
+ }
+
+ private sealed class Initialization : IDisposable
+ {
+ private int _disposed;
+
+ public void Dispose()
+ {
+ if (Interlocked.Exchange(ref _disposed, 1) != 0)
+ {
+ return;
+ }
+
+ lock (s_lock)
+ {
+ if (--s_initializationCount == 0)
+ {
+ Console.CancelKeyPress -= HandleCancelKeyPress;
+ AppDomain.CurrentDomain.ProcessExit -= HandleProcessExit;
+#if NET
+ s_sigTermRegistration?.Dispose();
+ s_sigTermRegistration = null;
+#endif
+ }
+ }
+ }
+ }
+
+ private sealed class SoftCancellationTimeoutOverride(int id) : IDisposable
+ {
+ private int _disposed;
+
+ public void Dispose()
+ {
+ if (Interlocked.Exchange(ref _disposed, 1) != 0)
+ {
+ return;
+ }
+
+ lock (s_lock)
+ {
+ s_softCancellationTimeoutOverrides.Remove(id);
+ ScheduleForcefulCancellation_NoLock();
+ }
+ }
+ }
+}
diff --git a/src/Cli/Microsoft.DotNet.Cli.Utils/ProcessReaper.cs b/src/Cli/Microsoft.DotNet.Cli.Utils/ProcessReaper.cs
index 4a22431cd14d..40826bd7aca1 100644
--- a/src/Cli/Microsoft.DotNet.Cli.Utils/ProcessReaper.cs
+++ b/src/Cli/Microsoft.DotNet.Cli.Utils/ProcessReaper.cs
@@ -30,6 +30,7 @@ namespace Microsoft.DotNet.Cli.Utils;
///
internal class ProcessReaper : IDisposable
{
+ private static readonly TimeSpan s_forcefulSigTermGracePeriod = TimeSpan.FromSeconds(1);
private readonly Process _process;
#if TARGET_WINDOWS
@@ -69,6 +70,17 @@ public override void NotifyProcessStarted()
}
}
+ public override void TerminateProcess()
+ {
+ if (_job is not null &&
+ PInvoke.TerminateJobObject((HANDLE)_job.DangerousGetHandle(), uint.MaxValue))
+ {
+ return;
+ }
+
+ base.TerminateProcess();
+ }
+
private static SafeWaitHandle? AssignProcessToJobObject(HANDLE process)
{
HANDLE job = PInvoke.CreateJobObject(null, null);
@@ -135,6 +147,8 @@ public override void Dispose()
#if !TARGET_WINDOWS && NET
private sealed class UnixProcessReaper : ProcessReaper
{
+ private readonly PosixSignalRegistration _sigTermRegistration;
+
// Coordinates Dispose (typically the main thread) with HandleProcessExit,
// which is raised on the AppDomain.ProcessExit thread when the CLI itself is
// shutting down (for example when a SIGTERM handler calls Environment.Exit).
@@ -147,14 +161,29 @@ private sealed class UnixProcessReaper : ProcessReaper
// ProcessExit callback that starts after Dispose has run simply becomes a no-op.
private readonly Lock _shutdownLock = new();
private bool _shuttingDown;
+ private int _sigTermRequested;
public UnixProcessReaper(Process process) : base(process)
{
AppDomain.CurrentDomain.ProcessExit += HandleProcessExit;
+ _sigTermRegistration = PosixSignalRegistration.Create(
+ PosixSignal.SIGTERM,
+ context =>
+ {
+ if (ProcessLifecycle.IsInitialized)
+ {
+ return;
+ }
+
+ context.Cancel = true;
+ Volatile.Write(ref _sigTermRequested, 1);
+ Environment.Exit(143);
+ });
}
public override void Dispose()
{
+ _sigTermRegistration.Dispose();
AppDomain.CurrentDomain.ProcessExit -= HandleProcessExit;
// If a ProcessExit driven shutdown is already running on another thread,
@@ -184,18 +213,34 @@ private void HandleProcessExit(object? sender, EventArgs args)
try
{
- // If the target is still running, forward SIGTERM so it can shut
- // down as well. Signal returns false if the process already exited,
- // and throws Win32Exception if the signal could not be delivered.
- if (!_process.WaitForExit(0))
+ ProcessExitStatus? exitStatus = null;
+ bool forwardSigTermWithGrace =
+ ProcessLifecycle.IsSigTermRequested ||
+ Volatile.Read(ref _sigTermRequested) != 0;
+
+ if (ProcessLifecycle.IsForcefulCancellationRequested &&
+ !ProcessLifecycle.IsSigTermRequested)
{
- _process.SafeHandle.Signal(PosixSignal.SIGTERM);
+ TerminateProcess();
+ }
+ else
+ {
+ // Forward SIGTERM before escalating so the child observes the
+ // same hard-shutdown signal as the CLI.
+ if (_process.Signal(PosixSignal.SIGTERM) &&
+ forwardSigTermWithGrace &&
+ !_process.TryWaitForExitStatus(s_forcefulSigTermGracePeriod, out exitStatus))
+ {
+ TerminateProcess();
+ }
}
- // If SIGTERM was ignored by the target, then we'll still wait.
- _process.WaitForExit();
+ exitStatus ??= _process.WaitForExitStatus();
- Environment.ExitCode = _process.ExitCode;
+ if (!ProcessLifecycle.IsSignalTerminationRequested)
+ {
+ Environment.ExitCode = exitStatus.ExitCode;
+ }
}
catch (InvalidOperationException)
{
@@ -250,11 +295,109 @@ private ProcessReaper(Process process)
///
public virtual void NotifyProcessStarted() { }
+ public virtual void TerminateProcess()
+ {
+#if NET
+ _process.Kill(entireProcessTree: true);
+#else
+ _process.Kill();
+#endif
+ }
+
public virtual void Dispose()
{
Console.CancelKeyPress -= HandleCancelKeyPress;
}
+ internal static void ForwardSigTermAndTerminate(IEnumerable processes)
+ {
+#if !TARGET_WINDOWS && NET
+ var activeProcesses = new List();
+ foreach (Process process in processes)
+ {
+ try
+ {
+ if (!process.HasExited)
+ {
+ activeProcesses.Add(process);
+ }
+ }
+ catch (Exception ex) when (ex is InvalidOperationException or Win32Exception)
+ {
+ Reporter.Verbose.WriteLine($"Exception checking child process state during SIGTERM forwarding:\n{ex}");
+ }
+ }
+
+ var signaledProcesses = new HashSet();
+
+ foreach (Process process in activeProcesses)
+ {
+ try
+ {
+ if (process.Signal(PosixSignal.SIGTERM))
+ {
+ signaledProcesses.Add(process);
+ }
+ }
+ catch (Exception ex) when (ex is InvalidOperationException or Win32Exception)
+ {
+ Reporter.Verbose.WriteLine($"Exception forwarding SIGTERM to child process:\n{ex}");
+ }
+ }
+
+ Stopwatch stopwatch = Stopwatch.StartNew();
+ foreach (Process process in activeProcesses)
+ {
+ if (signaledProcesses.Contains(process))
+ {
+ TimeSpan remaining = s_forcefulSigTermGracePeriod - stopwatch.Elapsed;
+ if (remaining > TimeSpan.Zero)
+ {
+ try
+ {
+ if (process.WaitForExit((int)Math.Ceiling(remaining.TotalMilliseconds)))
+ {
+ continue;
+ }
+ }
+ catch (InvalidOperationException ex)
+ {
+ Reporter.Verbose.WriteLine($"Exception waiting for child process after SIGTERM:\n{ex}");
+ continue;
+ }
+ }
+ }
+
+ try
+ {
+ if (!process.HasExited)
+ {
+ process.Kill(entireProcessTree: true);
+ }
+ }
+ catch (Exception ex) when (ex is InvalidOperationException or Win32Exception)
+ {
+ Reporter.Verbose.WriteLine($"Exception killing child process after SIGTERM grace period:\n{ex}");
+ }
+ }
+#else
+ foreach (Process process in processes)
+ {
+ try
+ {
+ if (!process.HasExited)
+ {
+ process.Kill();
+ }
+ }
+ catch (InvalidOperationException ex)
+ {
+ Reporter.Verbose.WriteLine($"Exception killing child process:\n{ex}");
+ }
+ }
+#endif
+ }
+
private void HandleCancelKeyPress(object? sender, ConsoleCancelEventArgs e)
{
// Ignore SIGINT/SIGQUIT so that the process can handle the signal
diff --git a/src/Cli/Microsoft.DotNet.Cli.Utils/Properties/AssemblyInfo.cs b/src/Cli/Microsoft.DotNet.Cli.Utils/Properties/AssemblyInfo.cs
index ff1652fc2ff9..bd2ebe1b9afa 100644
--- a/src/Cli/Microsoft.DotNet.Cli.Utils/Properties/AssemblyInfo.cs
+++ b/src/Cli/Microsoft.DotNet.Cli.Utils/Properties/AssemblyInfo.cs
@@ -12,6 +12,7 @@
[assembly: InternalsVisibleTo("dotnet-run.Tests, PublicKey=0024000004800000940000000602000000240000525341310004000001000100f33a29044fa9d740c9b3213a93e57c84b472c84e0b8a0e1ae48e67a9f8f6de9d5f7f3d52ac23e48ac51801f1dc950abe901da34d2a9e3baadb141a17c77ef3c565dd5ee5054b91cf63bb3c6ab83f72ab3aafe93d0fc3c2348b764fafb0b1c0733de51459aeab46580384bf9d74c4e28164b7cde247f891ba07891c9d872ad2bb")]
[assembly: InternalsVisibleTo("Microsoft.DotNet.Configurer, PublicKey=0024000004800000940000000602000000240000525341310004000001000100f33a29044fa9d740c9b3213a93e57c84b472c84e0b8a0e1ae48e67a9f8f6de9d5f7f3d52ac23e48ac51801f1dc950abe901da34d2a9e3baadb141a17c77ef3c565dd5ee5054b91cf63bb3c6ab83f72ab3aafe93d0fc3c2348b764fafb0b1c0733de51459aeab46580384bf9d74c4e28164b7cde247f891ba07891c9d872ad2bb")]
[assembly: InternalsVisibleTo("Microsoft.DotNet.Tools.Test, PublicKey=0024000004800000940000000602000000240000525341310004000001000100f33a29044fa9d740c9b3213a93e57c84b472c84e0b8a0e1ae48e67a9f8f6de9d5f7f3d52ac23e48ac51801f1dc950abe901da34d2a9e3baadb141a17c77ef3c565dd5ee5054b91cf63bb3c6ab83f72ab3aafe93d0fc3c2348b764fafb0b1c0733de51459aeab46580384bf9d74c4e28164b7cde247f891ba07891c9d872ad2bb")]
+[assembly: InternalsVisibleTo("Microsoft.DotNet.Cli.Utils.ProcessLifecycle.TestApp, PublicKey=0024000004800000940000000602000000240000525341310004000001000100f33a29044fa9d740c9b3213a93e57c84b472c84e0b8a0e1ae48e67a9f8f6de9d5f7f3d52ac23e48ac51801f1dc950abe901da34d2a9e3baadb141a17c77ef3c565dd5ee5054b91cf63bb3c6ab83f72ab3aafe93d0fc3c2348b764fafb0b1c0733de51459aeab46580384bf9d74c4e28164b7cde247f891ba07891c9d872ad2bb")]
[assembly: InternalsVisibleTo("Microsoft.DotNet.Cli.Utils.Tests, PublicKey=0024000004800000940000000602000000240000525341310004000001000100f33a29044fa9d740c9b3213a93e57c84b472c84e0b8a0e1ae48e67a9f8f6de9d5f7f3d52ac23e48ac51801f1dc950abe901da34d2a9e3baadb141a17c77ef3c565dd5ee5054b91cf63bb3c6ab83f72ab3aafe93d0fc3c2348b764fafb0b1c0733de51459aeab46580384bf9d74c4e28164b7cde247f891ba07891c9d872ad2bb")]
[assembly: InternalsVisibleTo("Microsoft.DotNet.TestFramework, PublicKey=0024000004800000940000000602000000240000525341310004000001000100f33a29044fa9d740c9b3213a93e57c84b472c84e0b8a0e1ae48e67a9f8f6de9d5f7f3d52ac23e48ac51801f1dc950abe901da34d2a9e3baadb141a17c77ef3c565dd5ee5054b91cf63bb3c6ab83f72ab3aafe93d0fc3c2348b764fafb0b1c0733de51459aeab46580384bf9d74c4e28164b7cde247f891ba07891c9d872ad2bb")]
[assembly: InternalsVisibleTo("Microsoft.DotNet.ShellShim.Tests, PublicKey=0024000004800000940000000602000000240000525341310004000001000100f33a29044fa9d740c9b3213a93e57c84b472c84e0b8a0e1ae48e67a9f8f6de9d5f7f3d52ac23e48ac51801f1dc950abe901da34d2a9e3baadb141a17c77ef3c565dd5ee5054b91cf63bb3c6ab83f72ab3aafe93d0fc3c2348b764fafb0b1c0733de51459aeab46580384bf9d74c4e28164b7cde247f891ba07891c9d872ad2bb")]
diff --git a/src/Cli/Microsoft.TemplateEngine.Cli/IReporterExtensions.cs b/src/Cli/Microsoft.TemplateEngine.Cli/IReporterExtensions.cs
index 6e62009ade59..124f66b093ff 100644
--- a/src/Cli/Microsoft.TemplateEngine.Cli/IReporterExtensions.cs
+++ b/src/Cli/Microsoft.TemplateEngine.Cli/IReporterExtensions.cs
@@ -1,7 +1,6 @@
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
-using System.Diagnostics;
using Microsoft.DotNet.Cli.Utils;
namespace Microsoft.TemplateEngine.Cli
@@ -23,21 +22,21 @@ internal static void WriteCommand(this IReporter reporter, string command, int i
}
///
- /// Writes formatted command output from .
+ /// Writes formatted command output from .
///
- internal static void WriteCommandOutput(this IReporter reporter, Process process)
+ internal static void WriteCommandOutput(this IReporter reporter, CommandResult commandResult)
{
- if (process.StartInfo.RedirectStandardOutput || process.StartInfo.RedirectStandardError)
+ if (commandResult.StartInfo.RedirectStandardOutput || commandResult.StartInfo.RedirectStandardError)
{
reporter.WriteLine(LocalizableStrings.CommandOutput);
}
- if (process.StartInfo.RedirectStandardOutput)
+ if (commandResult.StartInfo.RedirectStandardOutput)
{
- reporter.WriteStdOut(process.StandardOutput.ReadToEnd());
+ reporter.WriteStdOut(commandResult.StdOut ?? string.Empty);
}
- if (process.StartInfo.RedirectStandardError)
+ if (commandResult.StartInfo.RedirectStandardError)
{
- reporter.WriteStdErr(process.StandardError.ReadToEnd());
+ reporter.WriteStdErr(commandResult.StdErr ?? string.Empty);
}
}
diff --git a/src/Cli/Microsoft.TemplateEngine.Cli/PostActionDispatcher.cs b/src/Cli/Microsoft.TemplateEngine.Cli/PostActionDispatcher.cs
index c6f113525312..c9ed36da0249 100644
--- a/src/Cli/Microsoft.TemplateEngine.Cli/PostActionDispatcher.cs
+++ b/src/Cli/Microsoft.TemplateEngine.Cli/PostActionDispatcher.cs
@@ -66,7 +66,7 @@ internal PostActionDispatcher(IEngineEnvironmentSettings environment, Func set to true, the result will be anyway.
/// Note that is a flags enum, and can contain multiple status if multiple post actions failed with different reason.
///
- internal PostActionExecutionStatus Process(ITemplateCreationResult creationResult, bool isDryRun, AllowRunScripts canRunScripts)
+ internal PostActionExecutionStatus Process(ITemplateCreationResult creationResult, bool isDryRun, AllowRunScripts canRunScripts, CancellationToken cancellationToken)
{
_ = creationResult ?? throw new ArgumentNullException(nameof(creationResult));
_ = creationResult.CreationEffects ?? throw new ArgumentNullException(nameof(creationResult.CreationEffects));
@@ -134,7 +134,7 @@ internal PostActionExecutionStatus Process(ITemplateCreationResult creationResul
}
else if (canRunScripts == AllowRunScripts.Yes)
{
- result |= ProcessAction(creationResult.CreationEffects, creationResult.CreationResult!, creationResult.OutputBaseDirectory, action, actionProcessor);
+ result |= ProcessAction(creationResult.CreationEffects, creationResult.CreationResult!, creationResult.OutputBaseDirectory, action, actionProcessor, cancellationToken);
}
else if (canRunScripts == AllowRunScripts.Prompt)
{
@@ -143,7 +143,7 @@ internal PostActionExecutionStatus Process(ITemplateCreationResult creationResul
// Otherwise return cancelled, indicating the action was not run.
if (AskUserIfActionShouldRun(action))
{
- result |= ProcessAction(creationResult.CreationEffects, creationResult.CreationResult!, creationResult.OutputBaseDirectory, action, actionProcessor);
+ result |= ProcessAction(creationResult.CreationEffects, creationResult.CreationResult!, creationResult.OutputBaseDirectory, action, actionProcessor, cancellationToken);
}
else
{
@@ -154,7 +154,7 @@ internal PostActionExecutionStatus Process(ITemplateCreationResult creationResul
}
else // other post action
{
- result |= ProcessAction(creationResult.CreationEffects, creationResult.CreationResult!, creationResult.OutputBaseDirectory, action, actionProcessor);
+ result |= ProcessAction(creationResult.CreationEffects, creationResult.CreationResult!, creationResult.OutputBaseDirectory, action, actionProcessor, cancellationToken);
}
if (result != PostActionExecutionStatus.Success)
{
@@ -213,13 +213,14 @@ private PostActionExecutionStatus ProcessAction(
ICreationResult creationResult,
string outputBaseDirectory,
IPostAction action,
- IPostActionProcessor actionProcessor)
+ IPostActionProcessor actionProcessor,
+ CancellationToken cancellationToken)
{
//catch all exceptions on post action execution
//post actions can be added using components and it's not sure if they handle exceptions properly
try
{
- if (actionProcessor.Process(_environment, action, creationEffects, creationResult, outputBaseDirectory))
+ if (actionProcessor.Process(_environment, action, creationEffects, creationResult, outputBaseDirectory, cancellationToken))
{
return PostActionExecutionStatus.Success;
}
@@ -228,7 +229,7 @@ private PostActionExecutionStatus ProcessAction(
DisplayInstructionsForAction(action, useErrorOutput: true);
return PostActionExecutionStatus.Failure;
}
- catch (Exception e)
+ catch (Exception e) when (e is not OperationCanceledException)
{
Reporter.Error.WriteLine(LocalizableStrings.PostActionFailedInstructionHeader);
Reporter.Verbose.WriteLine(LocalizableStrings.Generic_Details, e.ToString());
diff --git a/src/Cli/Microsoft.TemplateEngine.Cli/PostActionProcessors/AddJsonPropertyPostActionProcessor.cs b/src/Cli/Microsoft.TemplateEngine.Cli/PostActionProcessors/AddJsonPropertyPostActionProcessor.cs
index 184eac990168..9486b540c6f5 100644
--- a/src/Cli/Microsoft.TemplateEngine.Cli/PostActionProcessors/AddJsonPropertyPostActionProcessor.cs
+++ b/src/Cli/Microsoft.TemplateEngine.Cli/PostActionProcessors/AddJsonPropertyPostActionProcessor.cs
@@ -83,7 +83,8 @@ protected override bool ProcessInternal(
IPostAction action,
ICreationEffects creationEffects,
ICreationResult templateCreationResult,
- string outputBasePath)
+ string outputBasePath,
+ CancellationToken cancellationToken)
{
if (!action.Args.TryGetValue(JsonFileNameArgument, out string? jsonFileName))
{
diff --git a/src/Cli/Microsoft.TemplateEngine.Cli/PostActionProcessors/ChmodPostActionProcessor.cs b/src/Cli/Microsoft.TemplateEngine.Cli/PostActionProcessors/ChmodPostActionProcessor.cs
index 3fb827553386..0c3797f63653 100644
--- a/src/Cli/Microsoft.TemplateEngine.Cli/PostActionProcessors/ChmodPostActionProcessor.cs
+++ b/src/Cli/Microsoft.TemplateEngine.Cli/PostActionProcessors/ChmodPostActionProcessor.cs
@@ -14,7 +14,7 @@ internal class ChmodPostActionProcessor : PostActionProcessorBase
public override Guid Id => ActionProcessorId;
- protected override bool ProcessInternal(IEngineEnvironmentSettings environment, IPostAction actionConfig, ICreationEffects creationEffects, ICreationResult templateCreationResult, string outputBasePath)
+ protected override bool ProcessInternal(IEngineEnvironmentSettings environment, IPostAction actionConfig, ICreationEffects creationEffects, ICreationResult templateCreationResult, string outputBasePath, CancellationToken cancellationToken)
{
bool allSucceeded = true;
foreach (KeyValuePair entry in actionConfig.Args)
diff --git a/src/Cli/Microsoft.TemplateEngine.Cli/PostActionProcessors/IPostActionProcessor.cs b/src/Cli/Microsoft.TemplateEngine.Cli/PostActionProcessors/IPostActionProcessor.cs
index 186845e014bb..e6e350290851 100644
--- a/src/Cli/Microsoft.TemplateEngine.Cli/PostActionProcessors/IPostActionProcessor.cs
+++ b/src/Cli/Microsoft.TemplateEngine.Cli/PostActionProcessors/IPostActionProcessor.cs
@@ -18,7 +18,8 @@ public interface IPostActionProcessor : IIdentifiedComponent
/// the results of the template dry run.
/// the results of the template instantiation.
/// the output directory the template was instantiated to.
+ /// token observed while processing the post action.
/// true if the post action is executed successfully, false otherwise.
- bool Process(IEngineEnvironmentSettings environment, IPostAction action, ICreationEffects creationEffects, ICreationResult templateCreationResult, string outputBasePath);
+ bool Process(IEngineEnvironmentSettings environment, IPostAction action, ICreationEffects creationEffects, ICreationResult templateCreationResult, string outputBasePath, CancellationToken cancellationToken);
}
}
diff --git a/src/Cli/Microsoft.TemplateEngine.Cli/PostActionProcessors/InstructionDisplayPostActionProcessor.cs b/src/Cli/Microsoft.TemplateEngine.Cli/PostActionProcessors/InstructionDisplayPostActionProcessor.cs
index 2e57e4b0f9a2..a2006a292110 100644
--- a/src/Cli/Microsoft.TemplateEngine.Cli/PostActionProcessors/InstructionDisplayPostActionProcessor.cs
+++ b/src/Cli/Microsoft.TemplateEngine.Cli/PostActionProcessors/InstructionDisplayPostActionProcessor.cs
@@ -13,7 +13,7 @@ internal class InstructionDisplayPostActionProcessor : PostActionProcessorBase
public override Guid Id => ActionProcessorId;
- protected override bool ProcessInternal(IEngineEnvironmentSettings environment, IPostAction actionConfig, ICreationEffects creationEffects, ICreationResult templateCreationResult, string outputBasePath)
+ protected override bool ProcessInternal(IEngineEnvironmentSettings environment, IPostAction actionConfig, ICreationEffects creationEffects, ICreationResult templateCreationResult, string outputBasePath, CancellationToken cancellationToken)
{
Reporter.Output.WriteLine(LocalizableStrings.PostActionDescription, actionConfig.Description);
Reporter.Output.WriteLine(LocalizableStrings.PostActionInstructions, actionConfig.ManualInstructions);
diff --git a/src/Cli/Microsoft.TemplateEngine.Cli/PostActionProcessors/PostActionProcessorBase.cs b/src/Cli/Microsoft.TemplateEngine.Cli/PostActionProcessors/PostActionProcessorBase.cs
index 35e41b8652a3..3df751a5db19 100644
--- a/src/Cli/Microsoft.TemplateEngine.Cli/PostActionProcessors/PostActionProcessorBase.cs
+++ b/src/Cli/Microsoft.TemplateEngine.Cli/PostActionProcessors/PostActionProcessorBase.cs
@@ -17,14 +17,15 @@ public bool Process(
IPostAction action,
ICreationEffects creationEffects,
ICreationResult templateCreationResult,
- string outputBasePath)
+ string outputBasePath,
+ CancellationToken cancellationToken)
{
if (string.IsNullOrWhiteSpace(outputBasePath))
{
throw new ArgumentException($"'{nameof(outputBasePath)}' cannot be null or whitespace.", nameof(outputBasePath));
}
outputBasePath = Path.GetFullPath(outputBasePath);
- return ProcessInternal(environment, action, creationEffects, templateCreationResult, outputBasePath);
+ return ProcessInternal(environment, action, creationEffects, templateCreationResult, outputBasePath, cancellationToken);
}
///
@@ -118,7 +119,8 @@ protected abstract bool ProcessInternal(
IPostAction action,
ICreationEffects creationEffects,
ICreationResult templateCreationResult,
- string outputBasePath);
+ string outputBasePath,
+ CancellationToken cancellationToken);
private static bool TryParseAsJson(string targetFiles, out IReadOnlyList paths)
{
diff --git a/src/Cli/Microsoft.TemplateEngine.Cli/PostActionProcessors/ProcessStartPostActionProcessor.cs b/src/Cli/Microsoft.TemplateEngine.Cli/PostActionProcessors/ProcessStartPostActionProcessor.cs
index b09219d2b17a..575c78a02022 100644
--- a/src/Cli/Microsoft.TemplateEngine.Cli/PostActionProcessors/ProcessStartPostActionProcessor.cs
+++ b/src/Cli/Microsoft.TemplateEngine.Cli/PostActionProcessors/ProcessStartPostActionProcessor.cs
@@ -10,11 +10,23 @@ namespace Microsoft.TemplateEngine.Cli.PostActionProcessors
{
internal class ProcessStartPostActionProcessor : PostActionProcessorBase
{
+ private readonly Func _commandFactory;
+
internal static readonly Guid ActionProcessorId = new("3A7C4B45-1F5D-4A30-959A-51B88E82B5D2");
+ public ProcessStartPostActionProcessor()
+ : this(process => new Command(process))
+ {
+ }
+
+ internal ProcessStartPostActionProcessor(Func commandFactory)
+ {
+ _commandFactory = commandFactory;
+ }
+
public override Guid Id => ActionProcessorId;
- protected override bool ProcessInternal(IEngineEnvironmentSettings environment, IPostAction actionConfig, ICreationEffects creationEffects, ICreationResult templateCreationResult, string outputBasePath)
+ protected override bool ProcessInternal(IEngineEnvironmentSettings environment, IPostAction actionConfig, ICreationEffects creationEffects, ICreationResult templateCreationResult, string outputBasePath, CancellationToken cancellationToken)
{
if (!actionConfig.Args.TryGetValue("executable", out string? executable) || string.IsNullOrWhiteSpace(executable))
{
@@ -50,25 +62,27 @@ protected override bool ProcessInternal(IEngineEnvironmentSettings environment,
Reporter.Output.WriteLine(LocalizableStrings.RunningCommand, command);
string resolvedExecutablePath = ResolveExecutableFilePath(environment.Host.FileSystem, executable, outputBasePath);
- Process? commandResult = System.Diagnostics.Process.Start(new ProcessStartInfo
+ using Process process = new()
{
- RedirectStandardError = redirectStandardError,
- RedirectStandardOutput = redirectStandardOutput,
- UseShellExecute = false,
- CreateNoWindow = false,
- WorkingDirectory = outputBasePath,
- FileName = resolvedExecutablePath,
- Arguments = args
- });
-
- if (commandResult == null)
+ StartInfo = new ProcessStartInfo
+ {
+ UseShellExecute = false,
+ CreateNoWindow = false,
+ WorkingDirectory = outputBasePath,
+ FileName = resolvedExecutablePath,
+ Arguments = args
+ }
+ };
+ ICommand commandToExecute = _commandFactory(process);
+ if (redirectStandardOutput)
{
- Reporter.Error.WriteLine(LocalizableStrings.CommandFailed);
- Reporter.Verbose.WriteLine("Unable to start sub-process.");
- return false;
+ commandToExecute.CaptureStdOut();
}
-
- commandResult.WaitForExit();
+ if (redirectStandardError)
+ {
+ commandToExecute.CaptureStdErr();
+ }
+ CommandResult commandResult = commandToExecute.Execute(cancellationToken);
if (commandResult.ExitCode != 0)
{
@@ -83,7 +97,7 @@ protected override bool ProcessInternal(IEngineEnvironmentSettings environment,
return true;
}
}
- catch (Exception ex)
+ catch (Exception ex) when (ex is not OperationCanceledException)
{
Reporter.Error.WriteLine(LocalizableStrings.CommandFailed);
Reporter.Error.WriteLine(ex.Message);
diff --git a/src/Cli/Microsoft.TemplateEngine.Cli/TemplateInvoker.cs b/src/Cli/Microsoft.TemplateEngine.Cli/TemplateInvoker.cs
index bec7b86fe9f7..99f5d33761af 100644
--- a/src/Cli/Microsoft.TemplateEngine.Cli/TemplateInvoker.cs
+++ b/src/Cli/Microsoft.TemplateEngine.Cli/TemplateInvoker.cs
@@ -57,11 +57,39 @@ internal async Task InvokeTemplateAsync(TemplateCommandArgs te
string? packageName = string.IsNullOrEmpty(templatePackage?.Identifier) ? null : Sha256Hasher.HashWithNormalizedCasing(templatePackage.Identifier);
string? packageVersion = string.IsNullOrEmpty(templatePackage?.Version) ? null : Sha256Hasher.HashWithNormalizedCasing(templatePackage.Version);
+ return await InvokeTemplateAsync(
+ () => CreateTemplateAsync(templateArgs, cancellationToken),
+ success => TelemetryEventEntry.TrackEvent(
+ TelemetryConstants.CreateEvent,
+ new Dictionary
+ {
+ { TelemetryConstants.Language, templateLanguage },
+ { TelemetryConstants.ArgError, "False" },
+ { TelemetryConstants.Framework, framework },
+ { TelemetryConstants.TemplateName, templateName },
+ { TelemetryConstants.TemplateShortName, templateShortNames },
+ { TelemetryConstants.PackageName, packageName },
+ { TelemetryConstants.PackageVersion, packageVersion },
+ { TelemetryConstants.IsTemplateThirdParty, (!isMicrosoftAuthored).ToString() },
+ { TelemetryConstants.CreationResult, success.ToString() },
+ { TelemetryConstants.Auth, auth }
+ })).ConfigureAwait(false);
+ }
+
+ internal static async Task InvokeTemplateAsync(
+ Func> createTemplateAsync,
+ Action trackTelemetry)
+ {
bool success = true;
try
{
- return await CreateTemplateAsync(templateArgs, cancellationToken).ConfigureAwait(false);
+ return await createTemplateAsync().ConfigureAwait(false);
+ }
+ catch (OperationCanceledException)
+ {
+ success = false;
+ throw;
}
catch (ContentGenerationException cx)
{
@@ -78,28 +106,13 @@ internal async Task InvokeTemplateAsync(TemplateCommandArgs te
{
success = false;
Reporter.Error.WriteLine(ex.Message.Bold().Red());
+ return NewCommandStatus.CreateFailed;
}
finally
{
- TelemetryEventEntry.TrackEvent(
- TelemetryConstants.CreateEvent,
- new Dictionary
- {
- { TelemetryConstants.Language, templateLanguage },
- { TelemetryConstants.ArgError, "False" },
- { TelemetryConstants.Framework, framework },
- { TelemetryConstants.TemplateName, templateName },
- { TelemetryConstants.TemplateShortName, templateShortNames },
- { TelemetryConstants.PackageName, packageName },
- { TelemetryConstants.PackageVersion, packageVersion },
- { TelemetryConstants.IsTemplateThirdParty, (!isMicrosoftAuthored).ToString() },
- { TelemetryConstants.CreationResult, success.ToString() },
- { TelemetryConstants.Auth, auth }
- });
+ trackTelemetry(success);
}
- return NewCommandStatus.CreateFailed;
-
}
private static string GetChangeString(ChangeKind kind)
@@ -218,7 +231,7 @@ private async Task CreateTemplateAsync(TemplateCommandArgs tem
Reporter.Output.WriteLine(LocalizableStrings.ThirdPartyNotices, templateArgs.Template.ThirdPartyNotices);
}
- return HandlePostActions(instantiateResult, templateArgs);
+ return HandlePostActions(instantiateResult, templateArgs, cancellationToken);
case CreationResultStatus.CreateFailed:
case CreationResultStatus.CondtionsEvaluationMismatch:
Reporter.Error.WriteLine(string.Format(LocalizableStrings.CreateFailed, resultTemplateName, instantiateResult.ErrorMessage).Bold().Red());
@@ -308,10 +321,10 @@ private async Task CreateTemplateAsync(TemplateCommandArgs tem
}
}
- private NewCommandStatus HandlePostActions(ITemplateCreationResult creationResult, TemplateCommandArgs args)
+ private NewCommandStatus HandlePostActions(ITemplateCreationResult creationResult, TemplateCommandArgs args, CancellationToken cancellationToken)
{
using var postActionActivity = Activities.Source.StartActivity("post-actions");
- PostActionExecutionStatus result = _postActionDispatcher.Process(creationResult, args.IsDryRun, args.AllowScripts ?? AllowRunScripts.Prompt);
+ PostActionExecutionStatus result = _postActionDispatcher.Process(creationResult, args.IsDryRun, args.AllowScripts ?? AllowRunScripts.Prompt, cancellationToken);
return result switch
{
diff --git a/src/Cli/dotnet-aot/DESIGN.md b/src/Cli/dotnet-aot/DESIGN.md
index cb42fd722b59..95ed38642d30 100644
--- a/src/Cli/dotnet-aot/DESIGN.md
+++ b/src/Cli/dotnet-aot/DESIGN.md
@@ -73,7 +73,7 @@ graph TD
AotCheck{"DOTNET_CLI_ENABLEAOT
not disabled?"}
Parse["Parser.Parse(args)"]
Fast{"Command handled
by AOT path?"}
- Invoke["Parser.Invoke()"]
+ Invoke["Parser.InvokeAsync(..., lifecycleToken)"]
HostInit["ManagedHost.RunApp()"]
Entry --> AotCheck
AotCheck -- "Yes" --> Parse --> Fast
@@ -142,7 +142,7 @@ command, ...) or an implicit file-based app (`dotnet app.cs`). The bridge's
the managed CLI uses — minus the MSBuild/NuGet project-tools resolver — via
`CommandResolver.TryResolveCommandSpec(new DefaultCommandResolverPolicy(), ...)`,
then invokes the resolved `CommandSpec` out-of-process through
-`CommandFactoryUsingResolver` + `Command.Execute()`. The resolution step is
+`CommandFactoryUsingResolver` + `Command.Execute(lifecycleToken)`. The resolution step is
side-effect free, so the bridge defers to the managed CLI whenever it cannot
handle the invocation: unsupported implicit file-based shapes, commands that only the full
project-tools resolver can find, anything that does
@@ -204,11 +204,11 @@ sequenceDiagram
alt DOTNET_CLI_ENABLEAOT enabled (default)
aot->>aot: Parser.Parse(args)
alt Built-in command handled by AOT
- aot->>aot: Parser.Invoke(parseResult)
+ aot->>aot: Parser.InvokeAsync(parseResult, lifecycleToken)
aot-->>dn: exit code
else External command that resolves in AOT (tool / PATH / app-base)
aot->>aot: TryInvokeExternalCommand → TryResolveCommandSpec
- aot->>tool: Command.Execute() (out of process)
+ aot->>tool: Command.Execute(lifecycleToken) (out of process)
tool-->>aot: exit code
aot-->>dn: exit code
else Command not handled, unresolved, or unsupported file-based shape
@@ -276,10 +276,18 @@ The two projects have **different entry-point shapes and do not share a
per-invocation telemetry/signal/first-run setup. It has no managed `Main` and
does not compile any `Program.cs`.
- **`src/Cli/dotnet/Program.cs`** — the managed CLI entry point with telemetry,
- signal handlers, and workload checks. It carries no `#if CLI_AOT` branches and
+ finalization, and workload checks. It carries no `#if CLI_AOT` branches and
is not linked into the AOT build. (The `hostfxr_run_app` fallback above invokes
*this* `Program.Main` from the managed `dotnet.dll` at runtime — not from the
AOT binary.)
+- **`Microsoft.DotNet.Cli.Utils.ProcessLifecycle`** — the shared managed/AOT
+ owner for Ctrl+C, SIGTERM, and process-exit cancellation. The first signal
+ cancels the token passed through command invocation and starts a two-second
+ forced-termination fallback; a repeated signal retains the operating system's
+ immediate termination behavior. While a launched child owns signal handling,
+ `ProcessReaper` suppresses lifecycle cancellation so Ctrl+C remains with the
+ child and SIGTERM is forwarded during process exit; an unresponsive child is
+ terminated after the same two-second timeout.
Code that genuinely needs to be identical between the two entry points lives in
`src/Cli/dotnet/CommandInvocation.cs` (`ExecuteInternalCommand`), which both
diff --git a/src/Cli/dotnet-aot/NativeEntryPoint.cs b/src/Cli/dotnet-aot/NativeEntryPoint.cs
index 8599bc342647..e83459429634 100644
--- a/src/Cli/dotnet-aot/NativeEntryPoint.cs
+++ b/src/Cli/dotnet-aot/NativeEntryPoint.cs
@@ -54,7 +54,40 @@ static int Execute(
args[i] = PlatformStringMarshaller.ConvertToManaged(argv[i]) ?? string.Empty;
}
- return ExecuteCore(hostPath, dotnetRoot, sdkDir, hostfxrPath, args);
+ return ExecuteCoreForNativeEntryPoint(
+ hostPath,
+ dotnetRoot,
+ sdkDir,
+ hostfxrPath,
+ args,
+ default);
+ }
+
+ internal static int ExecuteCoreForNativeEntryPoint(
+ string hostPath, string dotnetRoot, string sdkDir,
+ string hostfxrPath, string[] args,
+ CancellationToken cancellationToken)
+ {
+ try
+ {
+ return ExecuteCoreWithCancellation(
+ hostPath,
+ dotnetRoot,
+ sdkDir,
+ hostfxrPath,
+ args,
+ cancellationToken);
+ }
+ catch (OperationCanceledException) when (
+ ProcessLifecycle.TryGetSignalExitCode(ProcessLifecycle.CancellationToken, out int signalExitCode))
+ {
+ return signalExitCode;
+ }
+ catch (OperationCanceledException) when (cancellationToken.IsCancellationRequested)
+ {
+ // Exceptions cannot cross the native entry-point boundary.
+ return 1;
+ }
}
public static ITelemetryClient? TelemetryClient { get; private set; }
@@ -70,6 +103,18 @@ static int Execute(
internal static int ExecuteCore(
string hostPath, string dotnetRoot, string sdkDir,
string hostfxrPath, string[] args)
+ => ExecuteCoreWithCancellation(
+ hostPath,
+ dotnetRoot,
+ sdkDir,
+ hostfxrPath,
+ args,
+ default);
+
+ internal static int ExecuteCoreWithCancellation(
+ string hostPath, string dotnetRoot, string sdkDir,
+ string hostfxrPath, string[] args,
+ CancellationToken cancellationToken)
{
// Match the managed entry point before any localized resources are read. The AOT host does
// not run Program.Main, so it must apply DOTNET_CLI_UI_LANGUAGE/VSLANG itself.
@@ -185,6 +230,10 @@ internal static int ExecuteCore(
if (EnvironmentVariableParser.ParseBool(Environment.GetEnvironmentVariable(EnvironmentVariableNames.DOTNET_CLI_ENABLEAOT), defaultValue: true))
{
+ using IDisposable? processLifecycle =
+ cancellationToken == default ? ProcessLifecycle.Initialize() : null;
+ CancellationToken aotCancellationToken =
+ processLifecycle is null ? cancellationToken : ProcessLifecycle.CancellationToken;
ParseResult? parseResult = null;
using (var parse = Activities.Source.StartActivity("parse"))
{
@@ -220,7 +269,7 @@ internal static int ExecuteCore(
{
try
{
- exitCode = CommandInvocation.ExecuteInternalCommand(parseResult);
+ exitCode = CommandInvocation.ExecuteInternalCommand(parseResult, aotCancellationToken);
success = true;
aotHandledInProcess = true;
SendAotParserTelemetry(parseResult, globalJsonState);
@@ -236,7 +285,15 @@ internal static int ExecuteCore(
// or local tool, a command on the PATH, ...) or an implicit file-based app (`dotnet app.cs`).
// Resolve and invoke external commands in AOT when possible; defer file-based apps, legacy
// project tools, and anything that does not resolve to the managed CLI.
- else if (parseResult is not null && TryInvokeExternalCommand(parseResult, args, sdkDirectory, mainActivity, globalJsonState, out exitCode, out success))
+ else if (parseResult is not null && TryInvokeExternalCommand(
+ parseResult,
+ args,
+ sdkDirectory,
+ mainActivity,
+ globalJsonState,
+ aotCancellationToken,
+ out exitCode,
+ out success))
{
aotHandledInProcess = true;
return exitCode;
@@ -305,7 +362,15 @@ internal static int ExecuteCore(
/// unsupported file-based app shapes, legacy project tools, commands that do not resolve in AOT,
/// or any resolution error. External commands take precedence over implicit file-based apps.
///
- private static bool TryInvokeExternalCommand(ParseResult parseResult, string[] args, string sdkDir, Activity? mainActivity, string? globalJsonState, out int exitCode, out bool success)
+ private static bool TryInvokeExternalCommand(
+ ParseResult parseResult,
+ string[] args,
+ string sdkDir,
+ Activity? mainActivity,
+ string? globalJsonState,
+ CancellationToken cancellationToken,
+ out int exitCode,
+ out bool success)
{
exitCode = 1;
success = false;
@@ -346,7 +411,7 @@ private static bool TryInvokeExternalCommand(ParseResult parseResult, string[] a
{
try
{
- exitCode = AotRunCommand.Execute(fileBasedRunParseResult);
+ exitCode = AotRunCommand.Execute(fileBasedRunParseResult, cancellationToken);
success = true;
mainActivity?.SetDisplayName(fileBasedRunParseResult);
SendAotParserTelemetry(fileBasedRunParseResult, globalJsonState);
@@ -356,7 +421,7 @@ private static bool TryInvokeExternalCommand(ParseResult parseResult, string[] a
{
return false;
}
- catch (Exception exception)
+ catch (Exception exception) when (exception is not OperationCanceledException)
{
exitCode = Parser.ExceptionHandler(exception, fileBasedRunParseResult);
success = false;
@@ -392,11 +457,11 @@ private static bool TryInvokeExternalCommand(ParseResult parseResult, string[] a
try
{
Microsoft.DotNet.Cli.Utils.Command command = CommandFactoryUsingResolver.CreateOrThrow(commandName, commandSpec);
- exitCode = command.Execute().ExitCode;
+ exitCode = command.Execute(cancellationToken).ExitCode;
success = true;
return true;
}
- catch (Exception ex)
+ catch (Exception ex) when (ex is not OperationCanceledException)
{
// The command was resolved and may have already executed, so it must not be re-run via
// the managed CLI. Report the failure exactly as the managed invocation path would.
diff --git a/src/Cli/dotnet/BuildServer/IBuildServer.cs b/src/Cli/dotnet/BuildServer/IBuildServer.cs
index a46c2090d8d1..aee5bbedd727 100644
--- a/src/Cli/dotnet/BuildServer/IBuildServer.cs
+++ b/src/Cli/dotnet/BuildServer/IBuildServer.cs
@@ -11,5 +11,5 @@ internal interface IBuildServer
string Name { get; }
- void Shutdown();
+ void Shutdown(CancellationToken cancellationToken);
}
diff --git a/src/Cli/dotnet/BuildServer/MSBuildServer.cs b/src/Cli/dotnet/BuildServer/MSBuildServer.cs
index 2a837623b015..7256636e4ca8 100644
--- a/src/Cli/dotnet/BuildServer/MSBuildServer.cs
+++ b/src/Cli/dotnet/BuildServer/MSBuildServer.cs
@@ -13,8 +13,10 @@ internal class MSBuildServer : IBuildServer
public string Name => CliStrings.MSBuildServer;
- public void Shutdown()
+ public void Shutdown(CancellationToken cancellationToken)
{
+ cancellationToken.ThrowIfCancellationRequested();
BuildManager.DefaultBuildManager.ShutdownAllNodes();
+ cancellationToken.ThrowIfCancellationRequested();
}
}
diff --git a/src/Cli/dotnet/BuildServer/RazorServer.cs b/src/Cli/dotnet/BuildServer/RazorServer.cs
index 3773d1f1c115..4bf259b85103 100644
--- a/src/Cli/dotnet/BuildServer/RazorServer.cs
+++ b/src/Cli/dotnet/BuildServer/RazorServer.cs
@@ -22,8 +22,10 @@ internal class RazorServer(
public RazorPidFile PidFile { get; } = pidFile ?? throw new ArgumentNullException(nameof(pidFile));
- public void Shutdown()
+ public void Shutdown(CancellationToken cancellationToken)
{
+ cancellationToken.ThrowIfCancellationRequested();
+
if (!_fileSystem.File.Exists(PidFile.ServerPath.Value))
{
// The razor server path doesn't exist anymore so trying to shut it down would fail
@@ -45,7 +47,7 @@ public void Shutdown()
.CaptureStdOut()
.CaptureStdErr();
- var result = command.Execute();
+ var result = command.Execute(cancellationToken);
if (result.ExitCode != 0)
{
throw new BuildServerException(
diff --git a/src/Cli/dotnet/BuildServer/VBCSCompilerServer.cs b/src/Cli/dotnet/BuildServer/VBCSCompilerServer.cs
index e9c12cad1f40..1d22422ed72a 100644
--- a/src/Cli/dotnet/BuildServer/VBCSCompilerServer.cs
+++ b/src/Cli/dotnet/BuildServer/VBCSCompilerServer.cs
@@ -28,12 +28,12 @@ internal class VBCSCompilerServer(ICommandFactory commandFactory = null) : IBuil
public string Name => CliStrings.VBCSCompilerServer;
- public void Shutdown()
+ public void Shutdown(CancellationToken cancellationToken)
{
List errors = null;
// Shutdown the compiler from the SDK.
- execute(_commandFactory.Create("exec", [VBCSCompilerPath, s_shutdownArg]), ref errors);
+ execute(_commandFactory.Create("exec", [VBCSCompilerPath, s_shutdownArg]), cancellationToken, ref errors);
// Shutdown toolset compilers.
Reporter.Verbose.WriteLine($"Shutting down '{s_toolsetPackageName}' compilers.");
@@ -48,7 +48,7 @@ public void Shutdown()
Reporter.Verbose.WriteLine($"Found '{vbcsCompilerPath}'.");
if (File.Exists(vbcsCompilerPath))
{
- execute(CommandFactoryUsingResolver.Create(vbcsCompilerPath, [s_shutdownArg]), ref errors);
+ execute(CommandFactoryUsingResolver.Create(vbcsCompilerPath, [s_shutdownArg]), cancellationToken, ref errors);
}
}
}
@@ -61,13 +61,13 @@ public void Shutdown()
string.Join(Environment.NewLine, errors)));
}
- static void execute(ICommand command, ref List errors)
+ static void execute(ICommand command, CancellationToken cancellationToken, ref List errors)
{
command = command
.CaptureStdOut()
.CaptureStdErr();
- var result = command.Execute();
+ var result = command.Execute(cancellationToken);
if (result.ExitCode != 0)
{
errors ??= [];
diff --git a/src/Cli/dotnet/CliTransaction.cs b/src/Cli/dotnet/CliTransaction.cs
index ac970de9717e..6d04e439c8e8 100644
--- a/src/Cli/dotnet/CliTransaction.cs
+++ b/src/Cli/dotnet/CliTransaction.cs
@@ -3,6 +3,8 @@
#nullable disable
+using Microsoft.DotNet.Cli.Utils;
+
namespace Microsoft.DotNet.Cli;
internal interface ITransactionContext
@@ -45,6 +47,9 @@ public void Run(Action action)
}
catch (Exception)
{
+ using IDisposable softCancellationTimeout =
+ ProcessLifecycle.OverrideSoftCancellationTimeout(Timeout.InfiniteTimeSpan);
+
// Roll back transaction
RollbackStarted?.Invoke();
@@ -72,6 +77,9 @@ public void Run(Action action)
}
finally
{
+ using IDisposable softCancellationTimeout =
+ ProcessLifecycle.OverrideSoftCancellationTimeout(Timeout.InfiniteTimeSpan);
+
foreach (var cleanupAction in transactionContext.CleanupActions)
{
cleanupAction();
diff --git a/src/Cli/dotnet/CommandBase.cs b/src/Cli/dotnet/CommandBase.cs
index a1ca04d55522..c0099580a8bd 100644
--- a/src/Cli/dotnet/CommandBase.cs
+++ b/src/Cli/dotnet/CommandBase.cs
@@ -21,7 +21,7 @@ protected CommandBase(ParseResult parseResult)
protected CommandBase() { }
- public abstract int Execute();
+ public abstract int Execute(CancellationToken cancellationToken);
}
public abstract class CommandBase(ParseResult parseResult) : CommandBase(parseResult)
diff --git a/src/Cli/dotnet/CommandFactory/CommandResolution/MSBuildProject.cs b/src/Cli/dotnet/CommandFactory/CommandResolution/MSBuildProject.cs
index aa64c76d1e51..7ae054964278 100644
--- a/src/Cli/dotnet/CommandFactory/CommandResolution/MSBuildProject.cs
+++ b/src/Cli/dotnet/CommandFactory/CommandResolution/MSBuildProject.cs
@@ -147,8 +147,9 @@ public LockFile GetLockFile()
GetLockFilePathFromIntermediateBaseOutputPath();
return new LockFileFormat()
- .ReadWithLock(lockFilePath)
- .Result;
+ .ReadWithLock(lockFilePath, ProcessLifecycle.CancellationToken)
+ .GetAwaiter()
+ .GetResult();
}
public bool TryGetLockFile(out LockFile lockFile)
@@ -169,8 +170,9 @@ public bool TryGetLockFile(out LockFile lockFile)
}
lockFile = new LockFileFormat()
- .ReadWithLock(lockFilePath)
- .Result;
+ .ReadWithLock(lockFilePath, ProcessLifecycle.CancellationToken)
+ .GetAwaiter()
+ .GetResult();
return true;
}
diff --git a/src/Cli/dotnet/CommandFactory/CommandResolution/ProjectToolsCommandResolver.cs b/src/Cli/dotnet/CommandFactory/CommandResolution/ProjectToolsCommandResolver.cs
index e94272a4c385..7433916381e4 100644
--- a/src/Cli/dotnet/CommandFactory/CommandResolution/ProjectToolsCommandResolver.cs
+++ b/src/Cli/dotnet/CommandFactory/CommandResolution/ProjectToolsCommandResolver.cs
@@ -233,7 +233,7 @@ private static async Task FileExistsWithLock(string path)
return await ConcurrencyUtilities.ExecuteWithFileLockedAsync(
path,
lockedToken => Task.FromResult(File.Exists(path)),
- CancellationToken.None);
+ ProcessLifecycle.CancellationToken);
}
private bool TryGetToolLockFile(
@@ -245,7 +245,7 @@ private bool TryGetToolLockFile(
lockFile = null;
var lockFilePath = GetToolLockFilePath(toolLibrary, framework, nugetPackagesRoot);
- if (!FileExistsWithLock(lockFilePath).Result)
+ if (!FileExistsWithLock(lockFilePath).GetAwaiter().GetResult())
{
return false;
}
@@ -253,8 +253,9 @@ private bool TryGetToolLockFile(
try
{
lockFile = new LockFileFormat()
- .ReadWithLock(lockFilePath)
- .Result;
+ .ReadWithLock(lockFilePath, ProcessLifecycle.CancellationToken)
+ .GetAwaiter()
+ .GetResult();
}
catch (FileFormatException)
{
@@ -399,7 +400,7 @@ internal void GenerateDepsJsonFile(
{
result = forwardingAppWithoutLogging
.GetProcessStartInfo()
- .ExecuteAndCaptureOutput(out stdOut, out stdErr);
+ .ExecuteAndCaptureOutput(out stdOut, out stdErr, ProcessLifecycle.CancellationToken);
}
else
{
@@ -413,7 +414,7 @@ internal void GenerateDepsJsonFile(
Console.SetOut(outWriter);
Console.SetError(errWriter);
- result = forwardingAppWithoutLogging.Execute();
+ result = forwardingAppWithoutLogging.Execute(ProcessLifecycle.CancellationToken);
stdOut = outWriter.ToString();
stdErr = errWriter.ToString();
diff --git a/src/Cli/dotnet/CommandInvocation.cs b/src/Cli/dotnet/CommandInvocation.cs
index eb405317d8d5..3937d0b4d13c 100644
--- a/src/Cli/dotnet/CommandInvocation.cs
+++ b/src/Cli/dotnet/CommandInvocation.cs
@@ -18,20 +18,20 @@ namespace Microsoft.DotNet.Cli;
internal static class CommandInvocation
{
///
- /// Invokes a built-in command in-process via , applying the
+ /// Invokes a built-in command in-process via , applying the
/// same exit-code handling on both the managed CLI and the NativeAOT bridge (including the "new"
/// command's 127 adjustment and ). Errors are reported and
/// converted to an exit code, except that under NativeAOT a
/// is allowed to propagate so the bridge can fall back to hosting the managed CLI.
///
- internal static int ExecuteInternalCommand(ParseResult parseResult)
+ internal static int ExecuteInternalCommand(ParseResult parseResult, CancellationToken cancellationToken)
{
Debug.Assert(parseResult.CanBeInvoked());
int exitCode;
using var _ = Activities.Source.StartActivity("invocation");
try
{
- exitCode = Parser.Invoke(parseResult);
+ exitCode = Parser.InvokeAsync(parseResult, cancellationToken).GetAwaiter().GetResult();
if (parseResult.Errors.Any())
{
exitCode = AdjustExitCodeForNew();
@@ -45,6 +45,11 @@ internal static int ExecuteInternalCommand(ParseResult parseResult)
throw;
}
#endif
+ catch (OperationCanceledException) when (
+ ProcessLifecycle.TryGetSignalExitCode(cancellationToken, out int signalExitCode))
+ {
+ exitCode = signalExitCode;
+ }
catch (Exception exception)
{
exitCode = Parser.ExceptionHandler(exception, parseResult);
diff --git a/src/Cli/dotnet/Commands/Build/BuildCommand.cs b/src/Cli/dotnet/Commands/Build/BuildCommand.cs
index b0276710516d..d2b09b04d223 100644
--- a/src/Cli/dotnet/Commands/Build/BuildCommand.cs
+++ b/src/Cli/dotnet/Commands/Build/BuildCommand.cs
@@ -57,10 +57,10 @@ public static CommandBase FromParseResult(ParseResult parseResult, string? msbui
);
}
- public static int Run(ParseResult parseResult)
+ public static int Run(ParseResult parseResult, CancellationToken cancellationToken)
{
parseResult.HandleDebugSwitch();
- return FromParseResult(parseResult).Execute();
+ return FromParseResult(parseResult).Execute(cancellationToken);
}
}
diff --git a/src/Cli/dotnet/Commands/BuildServer/BuildServerCommandParser.cs b/src/Cli/dotnet/Commands/BuildServer/BuildServerCommandParser.cs
index 9d5495404745..c380a9aa393b 100644
--- a/src/Cli/dotnet/Commands/BuildServer/BuildServerCommandParser.cs
+++ b/src/Cli/dotnet/Commands/BuildServer/BuildServerCommandParser.cs
@@ -2,6 +2,7 @@
// The .NET Foundation licenses this file to you under the MIT license.
using System.CommandLine;
+using Microsoft.DotNet.Cli.CommandLine;
using Microsoft.DotNet.Cli.Commands.BuildServer.Shutdown;
using Microsoft.DotNet.Cli.Extensions;
@@ -12,6 +13,6 @@ internal static class BuildServerCommandParser
public static void ConfigureCommand(BuildServerCommandDefinition command)
{
command.SetAction(parseResult => parseResult.HandleMissingCommand());
- command.ShutdownCommand.SetAction(parseResult => new BuildServerShutdownCommand(parseResult).Execute());
+ command.ShutdownCommand.SetAction((parseResult, cancellationToken) => new BuildServerShutdownCommand(parseResult).Execute(cancellationToken));
}
}
diff --git a/src/Cli/dotnet/Commands/BuildServer/Shutdown/BuildServerShutdownCommand.cs b/src/Cli/dotnet/Commands/BuildServer/Shutdown/BuildServerShutdownCommand.cs
index 5ec87704b255..d50b90223d5e 100644
--- a/src/Cli/dotnet/Commands/BuildServer/Shutdown/BuildServerShutdownCommand.cs
+++ b/src/Cli/dotnet/Commands/BuildServer/Shutdown/BuildServerShutdownCommand.cs
@@ -48,9 +48,11 @@ public BuildServerShutdownCommand(
_reporter = reporter ?? Reporter.Output;
}
- public override int Execute()
+ public override int Execute(CancellationToken cancellationToken)
{
- var tasks = StartShutdown();
+ cancellationToken.ThrowIfCancellationRequested();
+
+ var tasks = StartShutdown(cancellationToken);
if (tasks.Count == 0)
{
@@ -61,13 +63,24 @@ public override int Execute()
bool success = true;
while (tasks.Count > 0)
{
- var index = WaitForResult([.. tasks.Select(t => t.Item2)]);
+ var index = WaitForResult([.. tasks.Select(t => t.Item2)], cancellationToken);
var (server, task) = tasks[index];
- if (task.IsFaulted)
+ if (task.IsCanceled)
+ {
+ task.GetAwaiter().GetResult();
+ }
+ else if (task.IsFaulted)
{
+ AggregateException exception = task.Exception;
+ if (exception.Flatten().InnerExceptions is [OperationCanceledException cancellationException] &&
+ cancellationException.CancellationToken == cancellationToken)
+ {
+ throw cancellationException;
+ }
+
success = false;
- WriteFailureMessage(server, task.Exception);
+ WriteFailureMessage(server, exception);
}
else
{
@@ -80,25 +93,25 @@ public override int Execute()
return success ? 0 : 1;
}
- private List<(IBuildServer, Task)> StartShutdown()
+ private List<(IBuildServer, Task)> StartShutdown(CancellationToken cancellationToken)
{
var tasks = new List<(IBuildServer, Task)>();
foreach (var server in _serverProvider.EnumerateBuildServers(_enumerationFlags))
{
WriteShutdownMessage(server);
- tasks.Add((server, Task.Run(() => server.Shutdown())));
+ tasks.Add((server, Task.Run(() => server.Shutdown(cancellationToken))));
}
return tasks;
}
- private int WaitForResult(Task[] tasks)
+ private int WaitForResult(Task[] tasks, CancellationToken cancellationToken)
{
if (_useOrderedWait)
{
- return Task.WaitAny(tasks.First());
+ return Task.WaitAny([tasks.First()], cancellationToken);
}
- return Task.WaitAny(tasks);
+ return Task.WaitAny(tasks, cancellationToken);
}
private void WriteShutdownMessage(IBuildServer server)
diff --git a/src/Cli/dotnet/Commands/Clean/CleanCommand.cs b/src/Cli/dotnet/Commands/Clean/CleanCommand.cs
index 5584a77f2461..22a1255bc96e 100644
--- a/src/Cli/dotnet/Commands/Clean/CleanCommand.cs
+++ b/src/Cli/dotnet/Commands/Clean/CleanCommand.cs
@@ -48,9 +48,9 @@ public static CommandBase FromParseResult(ParseResult result, string? msbuildPat
);
}
- public static int Run(ParseResult parseResult)
+ public static int Run(ParseResult parseResult, CancellationToken cancellationToken)
{
parseResult.HandleDebugSwitch();
- return FromParseResult(parseResult).Execute();
+ return FromParseResult(parseResult).Execute(cancellationToken);
}
}
diff --git a/src/Cli/dotnet/Commands/Clean/CleanCommandParser.cs b/src/Cli/dotnet/Commands/Clean/CleanCommandParser.cs
index 9322157a7f5c..1513705be6d2 100644
--- a/src/Cli/dotnet/Commands/Clean/CleanCommandParser.cs
+++ b/src/Cli/dotnet/Commands/Clean/CleanCommandParser.cs
@@ -14,6 +14,6 @@ public static void ConfigureCommand(CleanCommandDefinition command)
command.SetAction(CleanCommand.Run);
command.FrameworkOption.AddCompletions(CliCompletion.TargetFrameworksFromProjectFile);
command.ConfigurationOption.AddCompletions(CliCompletion.ConfigurationsFromProjectFileOrDefaults);
- command.FileBasedAppsCommand.SetAction(parseResult => new CleanFileBasedAppArtifactsCommand(parseResult).Execute());
+ command.FileBasedAppsCommand.SetAction((parseResult, cancellationToken) => new CleanFileBasedAppArtifactsCommand(parseResult).Execute(cancellationToken));
}
}
diff --git a/src/Cli/dotnet/Commands/Clean/FileBasedAppArtifacts/CleanFileBasedAppArtifactsCommand.cs b/src/Cli/dotnet/Commands/Clean/FileBasedAppArtifacts/CleanFileBasedAppArtifactsCommand.cs
index 847afe143398..65d255472098 100644
--- a/src/Cli/dotnet/Commands/Clean/FileBasedAppArtifacts/CleanFileBasedAppArtifactsCommand.cs
+++ b/src/Cli/dotnet/Commands/Clean/FileBasedAppArtifacts/CleanFileBasedAppArtifactsCommand.cs
@@ -13,7 +13,7 @@ namespace Microsoft.DotNet.Cli.Commands.Clean.FileBasedAppArtifacts;
internal sealed class CleanFileBasedAppArtifactsCommand(ParseResult parseResult) : CommandBase(parseResult)
{
- public override int Execute()
+ public override int Execute(CancellationToken cancellationToken)
{
bool dryRun = _parseResult.GetValue(Definition.DryRunOption);
diff --git a/src/Cli/dotnet/Commands/Format/FormatCommand.cs b/src/Cli/dotnet/Commands/Format/FormatCommand.cs
index 6cad47691e82..df537554fa9c 100644
--- a/src/Cli/dotnet/Commands/Format/FormatCommand.cs
+++ b/src/Cli/dotnet/Commands/Format/FormatCommand.cs
@@ -8,9 +8,9 @@ namespace Microsoft.DotNet.Cli.Commands.Format;
public sealed class FormatCommand(IEnumerable argsToForward)
: FormatForwardingApp(argsToForward)
{
- public static int Run(string[] args)
+ public static int Run(string[] args, CancellationToken cancellationToken)
{
DebugHelper.HandleDebugSwitch(ref args);
- return new FormatForwardingApp(args).Execute();
+ return new FormatForwardingApp(args).Execute(cancellationToken);
}
}
diff --git a/src/Cli/dotnet/Commands/Format/FormatCommandParser.cs b/src/Cli/dotnet/Commands/Format/FormatCommandParser.cs
index 1ea261db2bbf..cdd14168509a 100644
--- a/src/Cli/dotnet/Commands/Format/FormatCommandParser.cs
+++ b/src/Cli/dotnet/Commands/Format/FormatCommandParser.cs
@@ -2,6 +2,7 @@
// The .NET Foundation licenses this file to you under the MIT license.
using System.CommandLine;
+using Microsoft.DotNet.Cli.CommandLine;
namespace Microsoft.DotNet.Cli.Commands.Format;
@@ -9,6 +10,7 @@ internal static class FormatCommandParser
{
public static void ConfigureCommand(FormatCommandDefinition command)
{
- command.SetAction(parseResult => FormatCommand.Run(parseResult.GetValue(command.Arguments) ?? []));
+ command.SetAction((parseResult, cancellationToken) =>
+ FormatCommand.Run(parseResult.GetValue(command.Arguments) ?? [], cancellationToken));
}
}
diff --git a/src/Cli/dotnet/Commands/Fsi/FsiCommand.cs b/src/Cli/dotnet/Commands/Fsi/FsiCommand.cs
index d37b524438f6..cab7832d2373 100644
--- a/src/Cli/dotnet/Commands/Fsi/FsiCommand.cs
+++ b/src/Cli/dotnet/Commands/Fsi/FsiCommand.cs
@@ -7,9 +7,9 @@ namespace Microsoft.DotNet.Cli.Commands.Fsi;
public sealed class FsiCommand
{
- public static int Run(string[] args)
+ public static int Run(string[] args, CancellationToken cancellationToken)
{
DebugHelper.HandleDebugSwitch(ref args);
- return new FsiForwardingApp(args).Execute();
+ return new FsiForwardingApp(args).Execute(cancellationToken);
}
}
diff --git a/src/Cli/dotnet/Commands/Fsi/FsiCommandParser.cs b/src/Cli/dotnet/Commands/Fsi/FsiCommandParser.cs
index 1ac42cdc4a12..051cf81e5806 100644
--- a/src/Cli/dotnet/Commands/Fsi/FsiCommandParser.cs
+++ b/src/Cli/dotnet/Commands/Fsi/FsiCommandParser.cs
@@ -2,6 +2,7 @@
// The .NET Foundation licenses this file to you under the MIT license.
using System.CommandLine;
+using Microsoft.DotNet.Cli.CommandLine;
namespace Microsoft.DotNet.Cli.Commands.Fsi;
@@ -9,6 +10,7 @@ internal static class FsiCommandParser
{
public static void ConfigureCommand(FsiCommandDefinition command)
{
- command.SetAction(parseResult => FsiCommand.Run(parseResult.GetValue(command.Arguments) ?? []));
+ command.SetAction((parseResult, cancellationToken) =>
+ FsiCommand.Run(parseResult.GetValue(command.Arguments) ?? [], cancellationToken));
}
}
diff --git a/src/Cli/dotnet/Commands/Hidden/Add/AddCommandParser.cs b/src/Cli/dotnet/Commands/Hidden/Add/AddCommandParser.cs
index 23f41a0e945e..d4773cfc96af 100644
--- a/src/Cli/dotnet/Commands/Hidden/Add/AddCommandParser.cs
+++ b/src/Cli/dotnet/Commands/Hidden/Add/AddCommandParser.cs
@@ -2,6 +2,7 @@
// The .NET Foundation licenses this file to you under the MIT license.
using System.CommandLine;
+using Microsoft.DotNet.Cli.CommandLine;
using Microsoft.DotNet.Cli.Commands.Package;
using Microsoft.DotNet.Cli.Commands.Reference.Add;
using Microsoft.DotNet.Cli.Extensions;
@@ -15,6 +16,6 @@ public static void ConfigureCommand(AddCommandDefinition command)
command.SetAction(parseResult => parseResult.HandleMissingCommand());
PackageCommandParser.ConfigureAddCommand(command.PackageCommand);
- command.ReferenceCommand.SetAction(parseResult => new ReferenceAddCommand(parseResult).Execute());
+ command.ReferenceCommand.SetAction((parseResult, cancellationToken) => new ReferenceAddCommand(parseResult).Execute(cancellationToken));
}
}
diff --git a/src/Cli/dotnet/Commands/Hidden/List/ListCommandParser.cs b/src/Cli/dotnet/Commands/Hidden/List/ListCommandParser.cs
index d98fd9f6fc7c..16970557d8d6 100644
--- a/src/Cli/dotnet/Commands/Hidden/List/ListCommandParser.cs
+++ b/src/Cli/dotnet/Commands/Hidden/List/ListCommandParser.cs
@@ -2,6 +2,7 @@
// The .NET Foundation licenses this file to you under the MIT license.
using System.CommandLine;
+using Microsoft.DotNet.Cli.CommandLine;
using Microsoft.DotNet.Cli.Commands.Package.List;
using Microsoft.DotNet.Cli.Commands.Reference.List;
using Microsoft.DotNet.Cli.Extensions;
@@ -14,7 +15,7 @@ public static void ConfigureCommand(ListCommandDefinition command)
{
command.SetAction(parseResult => parseResult.HandleMissingCommand());
- command.PackageCommand.SetAction(parseResult => new PackageListCommand(parseResult).Execute());
- command.ReferenceCommand.SetAction(parseResult => new ReferenceListCommand(parseResult).Execute());
+ command.PackageCommand.SetAction((parseResult, cancellationToken) => new PackageListCommand(parseResult).Execute(cancellationToken));
+ command.ReferenceCommand.SetAction((parseResult, cancellationToken) => new ReferenceListCommand(parseResult).Execute(cancellationToken));
}
}
diff --git a/src/Cli/dotnet/Commands/Hidden/Remove/RemoveCommandParser.cs b/src/Cli/dotnet/Commands/Hidden/Remove/RemoveCommandParser.cs
index c8f558c1b7ff..c9d83b090453 100644
--- a/src/Cli/dotnet/Commands/Hidden/Remove/RemoveCommandParser.cs
+++ b/src/Cli/dotnet/Commands/Hidden/Remove/RemoveCommandParser.cs
@@ -2,6 +2,7 @@
// The .NET Foundation licenses this file to you under the MIT license.
using System.CommandLine;
+using Microsoft.DotNet.Cli.CommandLine;
using Microsoft.DotNet.Cli.Commands.Package.Remove;
using Microsoft.DotNet.Cli.Commands.Reference.Remove;
using Microsoft.DotNet.Cli.Extensions;
@@ -14,7 +15,7 @@ public static void ConfigureCommand(RemoveCommandDefinition command)
{
command.SetAction(parseResult => parseResult.HandleMissingCommand());
- command.PackageCommand.SetAction(parseResult => new PackageRemoveCommand(parseResult).Execute());
- command.ReferenceCommand.SetAction(parseResult => new ReferenceRemoveCommand(parseResult).Execute());
+ command.PackageCommand.SetAction((parseResult, cancellationToken) => new PackageRemoveCommand(parseResult).Execute(cancellationToken));
+ command.ReferenceCommand.SetAction((parseResult, cancellationToken) => new ReferenceRemoveCommand(parseResult).Execute(cancellationToken));
}
}
diff --git a/src/Cli/dotnet/Commands/MSBuild/MSBuildCommand.cs b/src/Cli/dotnet/Commands/MSBuild/MSBuildCommand.cs
index 57a922005fc2..ed4acedc667e 100644
--- a/src/Cli/dotnet/Commands/MSBuild/MSBuildCommand.cs
+++ b/src/Cli/dotnet/Commands/MSBuild/MSBuildCommand.cs
@@ -42,10 +42,10 @@ public static MSBuildCommand FromParseResult(ParseResult parseResult, string? ms
msbuildPath: msbuildPath);
}
- public static int Run(ParseResult parseResult)
+ public static int Run(ParseResult parseResult, CancellationToken cancellationToken)
{
parseResult.HandleDebugSwitch();
- return FromParseResult(parseResult).Execute();
+ return FromParseResult(parseResult).Execute(cancellationToken);
}
}
diff --git a/src/Cli/dotnet/Commands/MSBuild/MSBuildCommandParser.cs b/src/Cli/dotnet/Commands/MSBuild/MSBuildCommandParser.cs
index 662e6fbec7dc..de083b57fdcc 100644
--- a/src/Cli/dotnet/Commands/MSBuild/MSBuildCommandParser.cs
+++ b/src/Cli/dotnet/Commands/MSBuild/MSBuildCommandParser.cs
@@ -2,6 +2,7 @@
// The .NET Foundation licenses this file to you under the MIT license.
using System.CommandLine;
+using Microsoft.DotNet.Cli.CommandLine;
namespace Microsoft.DotNet.Cli.Commands.MSBuild;
diff --git a/src/Cli/dotnet/Commands/MSBuild/MSBuildForwardingApp.cs b/src/Cli/dotnet/Commands/MSBuild/MSBuildForwardingApp.cs
index 0cca20ca7f89..c6e0a2b2b1f3 100644
--- a/src/Cli/dotnet/Commands/MSBuild/MSBuildForwardingApp.cs
+++ b/src/Cli/dotnet/Commands/MSBuild/MSBuildForwardingApp.cs
@@ -28,6 +28,9 @@ namespace Microsoft.DotNet.Cli.Commands.MSBuild;
///
public class MSBuildForwardingApp : CommandBase
{
+ // MSBuild cancellation needs time to finish nodes and close loggers such as the binary logger.
+ internal static readonly TimeSpan BuildSoftCancellationTimeout = TimeSpan.FromSeconds(2);
+
private readonly MSBuildForwardingAppWithoutLogging _forwardingAppWithoutLogging;
///
@@ -130,15 +133,21 @@ private void InitializeRequiredEnvironmentVariables()
internal string[] GetArgumentTokensToMSBuild() => _forwardingAppWithoutLogging.GetAllArguments();
- public override int Execute() => Execute(workingDirectory: null);
+ public override int Execute(CancellationToken cancellationToken) => Execute(workingDirectory: null, cancellationToken);
- internal virtual int ExecuteOutOfProc(string workingDirectory) => Execute(workingDirectory);
+ internal virtual int ExecuteOutOfProc(string workingDirectory, CancellationToken cancellationToken) => Execute(workingDirectory, cancellationToken);
- private int Execute(string? workingDirectory)
+ private int Execute(string? workingDirectory, CancellationToken cancellationToken)
{
+ using IDisposable softCancellationTimeout =
+ ProcessLifecycle.OverrideSoftCancellationTimeout(BuildSoftCancellationTimeout);
+
// Ignore Ctrl-C for the remainder of the command's execution
// Forwarding commands will just spawn the child process and exit
Console.CancelKeyPress += (sender, e) => { e.Cancel = true; };
- return _forwardingAppWithoutLogging.Execute(workingDirectory);
+ return _forwardingAppWithoutLogging.Execute(
+ workingDirectory,
+ suspendSoftCancellationTimeout: false,
+ cancellationToken);
}
}
diff --git a/src/Cli/dotnet/Commands/New/DotnetCommandCallbacks.cs b/src/Cli/dotnet/Commands/New/DotnetCommandCallbacks.cs
index 84c961b615cb..4505ccbbac2a 100644
--- a/src/Cli/dotnet/Commands/New/DotnetCommandCallbacks.cs
+++ b/src/Cli/dotnet/Commands/New/DotnetCommandCallbacks.cs
@@ -13,7 +13,7 @@ namespace Microsoft.DotNet.Cli.Commands.New;
internal static class DotnetCommandCallbacks
{
- internal static bool AddPackageReference(string projectPath, string packageName, string? version)
+ internal static bool AddPackageReference(string projectPath, string packageName, string? version, CancellationToken cancellationToken)
{
PathUtility.EnsureAllPathsExist([projectPath], CliStrings.CommonFileNotFound, allowDirectories: false);
IEnumerable commandArgs = ["add", projectPath, "package", packageName];
@@ -28,10 +28,10 @@ internal static bool AddPackageReference(string projectPath, string packageName,
AddCommandParser.ConfigureCommand(addCommand);
var addPackageReferenceCommand = new PackageAddCommand(addCommand.Parse([.. commandArgs]));
- return addPackageReferenceCommand.Execute() == 0;
+ return addPackageReferenceCommand.Execute(cancellationToken) == 0;
}
- internal static bool AddProjectReference(string projectPath, string projectToAdd)
+ internal static bool AddProjectReference(string projectPath, string projectToAdd, CancellationToken cancellationToken)
{
PathUtility.EnsureAllPathsExist([projectPath], CliStrings.CommonFileNotFound, allowDirectories: false);
PathUtility.EnsureAllPathsExist([projectToAdd], CliStrings.CommonFileNotFound, allowDirectories: false);
@@ -41,17 +41,17 @@ internal static bool AddProjectReference(string projectPath, string projectToAdd
AddCommandParser.ConfigureCommand(addCommand);
var addProjectReferenceCommand = new ReferenceAddCommand(addCommand.Parse([.. commandArgs]));
- return addProjectReferenceCommand.Execute() == 0;
+ return addProjectReferenceCommand.Execute(cancellationToken) == 0;
}
- internal static bool RestoreProject(string pathToRestore)
+ internal static bool RestoreProject(string pathToRestore, CancellationToken cancellationToken)
{
PathUtility.EnsureAllPathsExist([pathToRestore], CliStrings.CommonFileNotFound, allowDirectories: true);
// for the implicit restore we do not want the terminal logger to emit any output unless there are errors
- return RestoreCommand.Run([pathToRestore, "-tlp:verbosity=quiet", "--no-logo"]) == 0;
+ return RestoreCommand.Run([pathToRestore, "-tlp:verbosity=quiet", "--no-logo"], cancellationToken) == 0;
}
- internal static bool AddProjectsToSolution(string solutionPath, IReadOnlyList projectsToAdd, string? solutionFolder, bool? inRoot)
+ internal static bool AddProjectsToSolution(string solutionPath, IReadOnlyList projectsToAdd, string? solutionFolder, bool? inRoot, CancellationToken cancellationToken)
{
PathUtility.EnsureAllPathsExist([solutionPath], CliStrings.CommonFileNotFound, allowDirectories: false);
PathUtility.EnsureAllPathsExist(projectsToAdd, CliStrings.CommonFileNotFound, allowDirectories: false);
@@ -70,6 +70,6 @@ internal static bool AddProjectsToSolution(string solutionPath, IReadOnlyList? addPackageReferenceCallback = null,
- Func? addProjectReferenceCallback = null) : PostActionProcessorBase
+ Func? addPackageReferenceCallback = null,
+ Func? addProjectReferenceCallback = null) : PostActionProcessorBase
{
- private readonly Func _addPackageReferenceCallback = addPackageReferenceCallback ?? DotnetCommandCallbacks.AddPackageReference;
- private readonly Func _addProjectReferenceCallback = addProjectReferenceCallback ?? DotnetCommandCallbacks.AddProjectReference;
+ private readonly Func _addPackageReferenceCallback = addPackageReferenceCallback ?? DotnetCommandCallbacks.AddPackageReference;
+ private readonly Func _addProjectReferenceCallback = addProjectReferenceCallback ?? DotnetCommandCallbacks.AddProjectReference;
public override Guid Id => ActionProcessorId;
@@ -32,7 +32,7 @@ internal static IReadOnlyList FindProjFileAtOrAbovePath(IPhysicalFileSys
}
}
- protected override bool ProcessInternal(IEngineEnvironmentSettings environment, IPostAction action, ICreationEffects creationEffects, ICreationResult templateCreationResult, string outputBasePath)
+ protected override bool ProcessInternal(IEngineEnvironmentSettings environment, IPostAction action, ICreationEffects creationEffects, ICreationResult templateCreationResult, string outputBasePath, CancellationToken cancellationToken)
{
IReadOnlyList? projectsToProcess = GetConfiguredFiles(action.Args, creationEffects, "targetFiles", outputBasePath);
@@ -80,7 +80,7 @@ protected override bool ProcessInternal(IEngineEnvironmentSettings environment,
bool success = true;
foreach (string projectFile in projectsToProcess)
{
- success &= AddReference(action, projectFile, outputBasePath, creationEffects);
+ success &= AddReference(action, projectFile, outputBasePath, creationEffects, cancellationToken);
if (!success)
{
@@ -111,7 +111,7 @@ private static IReadOnlyList FindExistingTargetFiles(IPhysicalFileSystem
return foundFiles ?? [];
}
- private bool AddReference(IPostAction actionConfig, string projectFile, string outputBasePath, ICreationEffects creationEffects)
+ private bool AddReference(IPostAction actionConfig, string projectFile, string outputBasePath, ICreationEffects creationEffects, CancellationToken cancellationToken)
{
if (actionConfig.Args == null || !actionConfig.Args.TryGetValue("reference", out string? referenceToAdd))
{
@@ -132,12 +132,12 @@ private bool AddReference(IPostAction actionConfig, string projectFile, string o
string relativeProjectReference = referenceNameChange ?? referenceToAdd;
referenceToAdd = Path.GetFullPath(relativeProjectReference, outputBasePath);
- return AddProjectReference(projectFile, referenceToAdd);
+ return AddProjectReference(projectFile, referenceToAdd, cancellationToken);
}
else if (string.Equals(referenceType, "package", StringComparison.OrdinalIgnoreCase))
{
actionConfig.Args.TryGetValue("version", out string? version);
- return AddPackageReference(projectFile, referenceToAdd, version);
+ return AddPackageReference(projectFile, referenceToAdd, version, cancellationToken);
}
else if (string.Equals(referenceType, "framework", StringComparison.OrdinalIgnoreCase))
{
@@ -151,7 +151,7 @@ private bool AddReference(IPostAction actionConfig, string projectFile, string o
}
}
- private bool AddPackageReference(string projectPath, string packageName, string? version)
+ private bool AddPackageReference(string projectPath, string packageName, string? version, CancellationToken cancellationToken)
{
try
{
@@ -163,7 +163,7 @@ private bool AddPackageReference(string projectPath, string packageName, string?
{
Reporter.Output.WriteLine(string.Format(CliCommandStrings.PostAction_AddReference_AddPackageReference_WithVersion, packageName, version, projectPath));
}
- bool succeeded = _addPackageReferenceCallback(projectPath, packageName, version);
+ bool succeeded = _addPackageReferenceCallback(projectPath, packageName, version, cancellationToken);
if (succeeded)
{
Reporter.Output.WriteLine(CliCommandStrings.PostAction_AddReference_Succeeded);
@@ -174,19 +174,19 @@ private bool AddPackageReference(string projectPath, string packageName, string?
}
return succeeded;
}
- catch (Exception e)
+ catch (Exception e) when (e is not OperationCanceledException)
{
Reporter.Error.WriteLine(string.Format(CliCommandStrings.PostAction_AddReference_AddPackageReference_Failed, e.Message));
return false;
}
}
- private bool AddProjectReference(string projectPath, string projectToAdd)
+ private bool AddProjectReference(string projectPath, string projectToAdd, CancellationToken cancellationToken)
{
try
{
Reporter.Output.WriteLine(string.Format(CliCommandStrings.PostAction_AddReference_AddProjectReference, projectToAdd, projectPath));
- bool succeeded = _addProjectReferenceCallback(projectPath, projectToAdd);
+ bool succeeded = _addProjectReferenceCallback(projectPath, projectToAdd, cancellationToken);
if (succeeded)
{
Reporter.Output.WriteLine(CliCommandStrings.PostAction_AddReference_Succeeded);
@@ -197,7 +197,7 @@ private bool AddProjectReference(string projectPath, string projectToAdd)
}
return succeeded;
}
- catch (Exception e)
+ catch (Exception e) when (e is not OperationCanceledException)
{
Reporter.Error.WriteLine(string.Format(CliCommandStrings.PostAction_AddReference_AddProjectReference_Failed, e.Message));
return false;
diff --git a/src/Cli/dotnet/Commands/New/PostActions/DotnetRestorePostActionProcessor.cs b/src/Cli/dotnet/Commands/New/PostActions/DotnetRestorePostActionProcessor.cs
index 189242819869..75f094ad0d79 100644
--- a/src/Cli/dotnet/Commands/New/PostActions/DotnetRestorePostActionProcessor.cs
+++ b/src/Cli/dotnet/Commands/New/PostActions/DotnetRestorePostActionProcessor.cs
@@ -7,15 +7,15 @@
namespace Microsoft.DotNet.Cli.Commands.New.PostActions;
-internal class DotnetRestorePostActionProcessor(Func? restoreCallback = null) : PostActionProcessorBase
+internal class DotnetRestorePostActionProcessor(Func? restoreCallback = null) : PostActionProcessorBase
{
- private readonly Func _restoreCallback = restoreCallback ?? DotnetCommandCallbacks.RestoreProject;
+ private readonly Func _restoreCallback = restoreCallback ?? DotnetCommandCallbacks.RestoreProject;
public override Guid Id => ActionProcessorId;
internal static Guid ActionProcessorId { get; } = new Guid("210D431B-A78B-4D2F-B762-4ED3E3EA9025");
- protected override bool ProcessInternal(IEngineEnvironmentSettings environment, IPostAction actionConfig, ICreationEffects creationEffects, ICreationResult templateCreationResult, string outputBasePath)
+ protected override bool ProcessInternal(IEngineEnvironmentSettings environment, IPostAction actionConfig, ICreationEffects creationEffects, ICreationResult templateCreationResult, string outputBasePath, CancellationToken cancellationToken)
{
bool allSucceeded = true;
IEnumerable targetFiles = GetConfiguredFiles(actionConfig.Args, creationEffects, "files", outputBasePath);
@@ -39,17 +39,17 @@ protected override bool ProcessInternal(IEngineEnvironmentSettings environment,
foreach (string pathToRestore in targetFiles)
{
- allSucceeded &= RestoreProject(pathToRestore);
+ allSucceeded &= RestoreProject(pathToRestore, cancellationToken);
}
return allSucceeded;
}
- private bool RestoreProject(string pathToRestore)
+ private bool RestoreProject(string pathToRestore, CancellationToken cancellationToken)
{
try
{
Reporter.Output.WriteLine(string.Format(CliCommandStrings.PostAction_Restore_Running, pathToRestore));
- bool succeeded = _restoreCallback(pathToRestore);
+ bool succeeded = _restoreCallback(pathToRestore, cancellationToken);
if (!succeeded)
{
Reporter.Error.WriteLine(CliCommandStrings.PostAction_Restore_Failed);
@@ -60,7 +60,7 @@ private bool RestoreProject(string pathToRestore)
}
return succeeded;
}
- catch (Exception e)
+ catch (Exception e) when (e is not OperationCanceledException)
{
Reporter.Error.WriteLine(string.Format(CliCommandStrings.PostAction_Restore_RestoreFailed, e.Message));
return false;
diff --git a/src/Cli/dotnet/Commands/New/PostActions/DotnetSlnPostActionProcessor.cs b/src/Cli/dotnet/Commands/New/PostActions/DotnetSlnPostActionProcessor.cs
index 960f68269035..54302530c399 100644
--- a/src/Cli/dotnet/Commands/New/PostActions/DotnetSlnPostActionProcessor.cs
+++ b/src/Cli/dotnet/Commands/New/PostActions/DotnetSlnPostActionProcessor.cs
@@ -9,9 +9,9 @@
namespace Microsoft.DotNet.Cli.Commands.New.PostActions;
-internal class DotnetSlnPostActionProcessor(Func, string?, bool?, bool>? addProjToSolutionCallback = null) : PostActionProcessorBase
+internal class DotnetSlnPostActionProcessor(Func, string?, bool?, CancellationToken, bool>? addProjToSolutionCallback = null) : PostActionProcessorBase
{
- private readonly Func, string?, bool?, bool> _addProjToSolutionCallback = addProjToSolutionCallback ?? DotnetCommandCallbacks.AddProjectsToSolution;
+ private readonly Func, string?, bool?, CancellationToken, bool> _addProjToSolutionCallback = addProjToSolutionCallback ?? DotnetCommandCallbacks.AddProjectsToSolution;
public override Guid Id => ActionProcessorId;
@@ -87,7 +87,7 @@ internal static bool TryGetProjectFilesToAdd(IPostAction actionConfig, ICreation
}
}
- protected override bool ProcessInternal(IEngineEnvironmentSettings environment, IPostAction action, ICreationEffects creationEffects, ICreationResult templateCreationResult, string outputBasePath)
+ protected override bool ProcessInternal(IEngineEnvironmentSettings environment, IPostAction action, ICreationEffects creationEffects, ICreationResult templateCreationResult, string outputBasePath, CancellationToken cancellationToken)
{
IReadOnlyList nearestSlnFilesFound = FindSolutionFilesAtOrAbovePath(environment.Host.FileSystem, outputBasePath);
if (nearestSlnFilesFound.Count != 1)
@@ -129,14 +129,14 @@ protected override bool ProcessInternal(IEngineEnvironmentSettings environment,
{
Reporter.Output.WriteLine(string.Format(CliCommandStrings.PostAction_AddProjToSln_Running, string.Join(" ", projectFiles), nearestSlnFilesFound[0], solutionFolder));
}
- return AddProjectsToSolution(nearestSlnFilesFound[0], projectFiles, solutionFolder, inRoot);
+ return AddProjectsToSolution(nearestSlnFilesFound[0], projectFiles, solutionFolder, inRoot, cancellationToken);
}
- private bool AddProjectsToSolution(string solutionPath, IReadOnlyList projectsToAdd, string? solutionFolder, bool? inRoot)
+ private bool AddProjectsToSolution(string solutionPath, IReadOnlyList projectsToAdd, string? solutionFolder, bool? inRoot, CancellationToken cancellationToken)
{
try
{
- bool succeeded = _addProjToSolutionCallback(solutionPath, projectsToAdd, solutionFolder, inRoot);
+ bool succeeded = _addProjToSolutionCallback(solutionPath, projectsToAdd, solutionFolder, inRoot, cancellationToken);
if (!succeeded)
{
Reporter.Error.WriteLine(CliCommandStrings.PostAction_AddProjToSln_Failed_NoReason);
diff --git a/src/Cli/dotnet/Commands/NuGet/NuGetCommand.cs b/src/Cli/dotnet/Commands/NuGet/NuGetCommand.cs
index 1a68c691d84f..dd7ea1519101 100644
--- a/src/Cli/dotnet/Commands/NuGet/NuGetCommand.cs
+++ b/src/Cli/dotnet/Commands/NuGet/NuGetCommand.cs
@@ -13,20 +13,21 @@ namespace Microsoft.DotNet.Cli.Commands.NuGet;
internal class NuGetCommand
{
- public static int Run(string[] args, bool isFileBasedApp = false)
+ public static int Run(string[] args, CancellationToken cancellationToken, bool isFileBasedApp = false)
{
#if CLI_AOT
// The in-process NuGet runner relies on NuGet.CommandLine.XPlat, which isn't AOT-compatible,
// so AOT always forwards to the out-of-process NuGet CLI.
- return Run(args, new NuGetCommandRunner());
+ return Run(args, new NuGetCommandRunner(), cancellationToken);
#else
return Run(args, isFileBasedApp
? new InProcessNuGetCommandRunner(NuGetVirtualProjectBuilder.Instance)
- : new NuGetCommandRunner());
+ : new NuGetCommandRunner(),
+ cancellationToken);
#endif
}
- public static int Run(ParseResult parseResult)
+ public static int Run(ParseResult parseResult, CancellationToken cancellationToken)
{
ICommandRunner runner;
@@ -46,10 +47,10 @@ public static int Run(ParseResult parseResult)
}
#endif
- return Run(parseResult.GetArguments(), runner);
+ return Run(parseResult.GetArguments(), runner, cancellationToken);
}
- public static int Run(string[] args, ICommandRunner nugetCommandRunner)
+ public static int Run(string[] args, ICommandRunner nugetCommandRunner, CancellationToken cancellationToken)
{
DebugHelper.HandleDebugSwitch(ref args);
@@ -63,16 +64,16 @@ public static int Run(string[] args, ICommandRunner nugetCommandRunner)
if (args[i] == "-?")
args[i] = "--help";
}
- return nugetCommandRunner.Run(args);
+ return nugetCommandRunner.Run(args, cancellationToken);
}
private class NuGetCommandRunner : ICommandRunner
{
- public int Run(string[] args)
+ public int Run(string[] args, CancellationToken cancellationToken)
{
var nugetApp = new NuGetForwardingApp(args);
nugetApp.WithEnvironmentVariable(EnvironmentVariableNames.DOTNET_HOST_PATH, GetDotnetPath());
- return nugetApp.Execute();
+ return nugetApp.Execute(cancellationToken);
}
}
@@ -84,13 +85,17 @@ private class InProcessNuGetCommandRunner(NuGetVirtualProjectBuilder virtualProj
"IL2026",
Justification =
"This runner is excluded from CLI_AOT builds")]
- public int Run(string[] args)
+ public int Run(string[] args, CancellationToken cancellationToken)
{
+ cancellationToken.ThrowIfCancellationRequested();
+
var originalDotNetHostPath = Environment.GetEnvironmentVariable(EnvironmentVariableNames.DOTNET_HOST_PATH);
Environment.SetEnvironmentVariable(EnvironmentVariableNames.DOTNET_HOST_PATH, GetDotnetPath());
try
{
- return global::NuGet.CommandLine.XPlat.Program.Run(args, virtualProjectBuilder);
+ int exitCode = global::NuGet.CommandLine.XPlat.Program.Run(args, virtualProjectBuilder);
+ cancellationToken.ThrowIfCancellationRequested();
+ return exitCode;
}
finally
{
diff --git a/src/Cli/dotnet/Commands/NuGet/NuGetCommandParser.cs b/src/Cli/dotnet/Commands/NuGet/NuGetCommandParser.cs
index c7de8029cbdd..153d11018685 100644
--- a/src/Cli/dotnet/Commands/NuGet/NuGetCommandParser.cs
+++ b/src/Cli/dotnet/Commands/NuGet/NuGetCommandParser.cs
@@ -2,6 +2,7 @@
// The .NET Foundation licenses this file to you under the MIT license.
using System.CommandLine;
+using Microsoft.DotNet.Cli.CommandLine;
namespace Microsoft.DotNet.Cli.Commands.NuGet;
@@ -17,4 +18,3 @@ public static void ConfigureCommand(Command command)
}
}
}
-
diff --git a/src/Cli/dotnet/Commands/Pack/PackCommand.cs b/src/Cli/dotnet/Commands/Pack/PackCommand.cs
index 3af1dc310118..8ca13c6cc285 100644
--- a/src/Cli/dotnet/Commands/Pack/PackCommand.cs
+++ b/src/Cli/dotnet/Commands/Pack/PackCommand.cs
@@ -23,13 +23,19 @@ public class PackCommand(
string? msbuildPath = null
) : RestoringCommand(msbuildArgs, noRestore, msbuildPath: msbuildPath)
{
- public static CommandBase FromArgs(string[] args, string? msbuildPath = null)
+ public static CommandBase FromArgs(
+ string[] args,
+ CancellationToken cancellationToken,
+ string? msbuildPath = null)
{
var parseResult = Parser.Parse(["dotnet", "pack", .. args]);
- return FromParseResult(parseResult, msbuildPath);
+ return FromParseResult(parseResult, cancellationToken, msbuildPath);
}
- public static CommandBase FromParseResult(ParseResult parseResult, string? msbuildPath = null)
+ public static CommandBase FromParseResult(
+ ParseResult parseResult,
+ CancellationToken cancellationToken,
+ string? msbuildPath = null)
{
var definition = (PackCommandDefinition)parseResult.CommandResult.Command;
@@ -68,7 +74,8 @@ public static CommandBase FromParseResult(ParseResult parseResult, string? msbui
new ReleasePropertyProjectLocator.DependentCommandOptions(
otherArgs,
parseResult.HasOption(definition.ConfigurationOption) ? parseResult.GetValue(definition.ConfigurationOption) : null
- )
+ ),
+ cancellationToken
);
return msbuildArgs.CloneWithAdditionalProperties(projectLocator.GetCustomDefaultConfigurationValueIfSpecified());
});
@@ -133,7 +140,7 @@ public static int RunPackCommand(ParseResult parseResult)
return 0;
}
- public static int Run(ParseResult parseResult)
+ public static int Run(ParseResult parseResult, CancellationToken cancellationToken)
{
var definition = (PackCommandDefinition)parseResult.CommandResult.Command;
@@ -148,6 +155,6 @@ public static int Run(ParseResult parseResult)
}
// Fallback to MSBuild-based packing
- return FromParseResult(parseResult).Execute();
+ return FromParseResult(parseResult, cancellationToken).Execute(cancellationToken);
}
}
diff --git a/src/Cli/dotnet/Commands/Package/Add/PackageAddCommand.cs b/src/Cli/dotnet/Commands/Package/Add/PackageAddCommand.cs
index 22cb8361f6c2..488403a92d7f 100644
--- a/src/Cli/dotnet/Commands/Package/Add/PackageAddCommand.cs
+++ b/src/Cli/dotnet/Commands/Package/Add/PackageAddCommand.cs
@@ -22,7 +22,7 @@ public PackageAddCommand(ParseResult parseResult)
_packageId = parseResult.GetValue(Definition.PackageIdArgument);
}
- public override int Execute()
+ public override int Execute(CancellationToken cancellationToken)
{
var (fileOrDirectory, allowedAppKinds) = PackageCommandParser.ProcessPathOptions(Definition.FileOption, Definition.ProjectOption, Definition.GetProjectOrFileArgument(), _parseResult);
@@ -61,7 +61,7 @@ public override int Execute()
throw new GracefulException(string.Format(CliCommandStrings.CmdDGFileIOException, projectFilePath), ioex);
}
- GetProjectDependencyGraph(projectFilePath, tempDgFilePath, isFileBasedApp);
+ GetProjectDependencyGraph(projectFilePath, tempDgFilePath, isFileBasedApp, cancellationToken);
}
var args = TransformArgs(
@@ -69,14 +69,17 @@ public override int Execute()
tempDgFilePath,
projectFilePath);
- var result = NuGetCommand.Run(args, isFileBasedApp);
-
- DisposeTemporaryFile(tempDgFilePath);
-
- return result;
+ try
+ {
+ return NuGetCommand.Run(args, cancellationToken, isFileBasedApp);
+ }
+ finally
+ {
+ DisposeTemporaryFile(tempDgFilePath);
+ }
}
- private static void GetProjectDependencyGraph(string projectFilePath, string dgFilePath, bool isFileBasedApp)
+ private static void GetProjectDependencyGraph(string projectFilePath, string dgFilePath, bool isFileBasedApp, CancellationToken cancellationToken)
{
int result;
if (isFileBasedApp)
@@ -96,7 +99,7 @@ private static void GetProjectDependencyGraph(string projectFilePath, string dgF
NoRestore = true,
NoCache = true,
NoWriteBuildMarkers = true,
- }.Execute();
+ }.Execute(cancellationToken);
}
else
{
@@ -122,7 +125,7 @@ private static void GetProjectDependencyGraph(string projectFilePath, string dgF
// Set verbosity to quiet to avoid cluttering the output for this 'inner' build
"-v:quiet"
- ]).Execute();
+ ]).Execute(cancellationToken);
}
if (result != 0)
diff --git a/src/Cli/dotnet/Commands/Package/List/PackageListCommand.cs b/src/Cli/dotnet/Commands/Package/List/PackageListCommand.cs
index a661412adc73..0b6edee25617 100644
--- a/src/Cli/dotnet/Commands/Package/List/PackageListCommand.cs
+++ b/src/Cli/dotnet/Commands/Package/List/PackageListCommand.cs
@@ -19,7 +19,7 @@ namespace Microsoft.DotNet.Cli.Commands.Package.List;
internal sealed class PackageListCommand(ParseResult parseResult) : CommandBase(parseResult)
{
- public override int Execute()
+ public override int Execute(CancellationToken cancellationToken)
{
var (fileOrDirectory, allowedAppKinds) = PackageCommandParser.ProcessPathOptions(Definition.FileOption, Definition.ProjectOption, Definition.GetProjectOrFileArgument(), _parseResult);
@@ -37,15 +37,15 @@ public override int Execute()
{
ReportOutputFormat formatOption = _parseResult.GetValue(Definition.FormatOption);
bool interactive = _parseResult.GetValue(Definition.InteractiveOption);
- restoreExitCode = RunRestore(projectFile, formatOption, interactive, isFileBasedApp);
+ restoreExitCode = RunRestore(projectFile, formatOption, interactive, isFileBasedApp, cancellationToken);
}
return restoreExitCode == 0
- ? NuGetCommand.Run(TransformArgs(projectFile), isFileBasedApp)
+ ? NuGetCommand.Run(TransformArgs(projectFile), cancellationToken, isFileBasedApp)
: restoreExitCode;
}
- private static int RunRestore(string projectOrSolution, ReportOutputFormat formatOption, bool interactive, bool isFileBasedApp)
+ private static int RunRestore(string projectOrSolution, ReportOutputFormat formatOption, bool interactive, bool isFileBasedApp, CancellationToken cancellationToken)
{
CommandBase command;
if (isFileBasedApp)
@@ -85,9 +85,10 @@ private static int RunRestore(string projectOrSolution, ReportOutputFormat forma
try
{
- exitCode = command.Execute();
+ cancellationToken.ThrowIfCancellationRequested();
+ exitCode = command.Execute(cancellationToken);
}
- catch (Exception)
+ catch (Exception ex) when (ex is not OperationCanceledException)
{
exitCode = 1;
}
diff --git a/src/Cli/dotnet/Commands/Package/PackageCommandParser.cs b/src/Cli/dotnet/Commands/Package/PackageCommandParser.cs
index 9144f5c2a3dd..1d2eb5ac1842 100644
--- a/src/Cli/dotnet/Commands/Package/PackageCommandParser.cs
+++ b/src/Cli/dotnet/Commands/Package/PackageCommandParser.cs
@@ -10,6 +10,7 @@
using Microsoft.DotNet.Cli.Commands.Package.Search;
using Microsoft.DotNet.Cli.Commands.Run;
using Microsoft.DotNet.Cli.Extensions;
+using Microsoft.DotNet.Cli.Utils;
using Microsoft.Extensions.EnvironmentAbstractions;
using NuGet.Versioning;
@@ -21,14 +22,14 @@ public static void ConfigureCommand(PackageCommandDefinition command)
{
command.SetAction((parseResult) => parseResult.HandleMissingCommand());
- command.RemoveCommand.SetAction(parseResult => new PackageRemoveCommand(parseResult).Execute());
- command.ListCommand.SetAction(parseResult => new PackageListCommand(parseResult).Execute());
+ command.RemoveCommand.SetAction((parseResult, cancellationToken) => new PackageRemoveCommand(parseResult).Execute(cancellationToken));
+ command.ListCommand.SetAction((parseResult, cancellationToken) => new PackageListCommand(parseResult).Execute(cancellationToken));
ConfigureAddCommand(command.AddCommand);
- command.SearchCommand.SetAction(parseResult =>
+ command.SearchCommand.SetAction((parseResult, cancellationToken) =>
{
var command = new PackageSearchCommand(parseResult);
- int exitCode = command.Execute();
+ int exitCode = command.Execute(cancellationToken);
if (exitCode == 1)
{
@@ -45,7 +46,10 @@ internal static void ConfigureAddCommand(PackageAddCommandDefinitionBase def)
{
// we should take --prerelease flags into account for version completion
var allowPrerelease = context.ParseResult.GetValue(def.PrereleaseOption);
- return QueryNuGet(context.WordToComplete, allowPrerelease, CancellationToken.None).Result.Select(packageId => new CompletionItem(packageId));
+ return QueryNuGet(context.WordToComplete, allowPrerelease, ProcessLifecycle.CancellationToken)
+ .GetAwaiter()
+ .GetResult()
+ .Select(packageId => new CompletionItem(packageId));
});
def.VersionOption.CompletionSources.Add(context =>
@@ -55,8 +59,9 @@ internal static void ConfigureAddCommand(PackageAddCommandDefinitionBase def)
{
// we should take --prerelease flags into account for version completion
var allowPrerelease = context.ParseResult.GetValue(def.PrereleaseOption);
- return QueryVersionsForPackage(packageId.Id, context.WordToComplete, allowPrerelease, CancellationToken.None)
- .Result
+ return QueryVersionsForPackage(packageId.Id, context.WordToComplete, allowPrerelease, ProcessLifecycle.CancellationToken)
+ .GetAwaiter()
+ .GetResult()
.Select(version => new CompletionItem(version.ToNormalizedString()));
}
else
@@ -65,7 +70,7 @@ internal static void ConfigureAddCommand(PackageAddCommandDefinitionBase def)
}
});
- def.SetAction(parseResult => new PackageAddCommand(parseResult).Execute());
+ def.SetAction((parseResult, cancellationToken) => new PackageAddCommand(parseResult).Execute(cancellationToken));
}
private static async Task> QueryNuGet(string packageStem, bool allowPrerelease, CancellationToken cancellationToken)
@@ -76,7 +81,7 @@ private static async Task> QueryNuGet(string packageStem, bo
var versions = await downloader.GetPackageIdsAsync(packageStem, allowPrerelease, cancellationToken: cancellationToken);
return versions;
}
- catch (Exception)
+ catch (Exception ex) when (ex is not OperationCanceledException)
{
return [];
}
@@ -90,7 +95,7 @@ private static async Task> QueryVersionsForPackage(str
var versions = await downloader.GetPackageVersionsAsync(new(packageId), versionFragment, allowPrerelease, cancellationToken: cancellationToken);
return versions;
}
- catch (Exception)
+ catch (Exception ex) when (ex is not OperationCanceledException)
{
return [];
}
diff --git a/src/Cli/dotnet/Commands/Package/Remove/PackageRemoveCommand.cs b/src/Cli/dotnet/Commands/Package/Remove/PackageRemoveCommand.cs
index 8c1901d13d06..53e145e2f072 100644
--- a/src/Cli/dotnet/Commands/Package/Remove/PackageRemoveCommand.cs
+++ b/src/Cli/dotnet/Commands/Package/Remove/PackageRemoveCommand.cs
@@ -15,7 +15,7 @@ internal sealed class PackageRemoveCommand(ParseResult parseResult) : CommandBas
{
private readonly PackageRemoveCommandDefinitionBase _definition = (PackageRemoveCommandDefinitionBase)parseResult.CommandResult.Command;
- public override int Execute()
+ public override int Execute(CancellationToken cancellationToken)
{
var arguments = _parseResult.GetValue(_definition.CmdPackageArgument) ?? [];
@@ -50,7 +50,7 @@ public override int Execute()
projectFilePath = Path.GetFullPath(projectFilePath);
}
- var result = NuGetCommand.Run(TransformArgs(packageToRemove, projectFilePath), isFileBasedApp);
+ var result = NuGetCommand.Run(TransformArgs(packageToRemove, projectFilePath), cancellationToken, isFileBasedApp);
return result;
}
diff --git a/src/Cli/dotnet/Commands/Package/Search/PackageSearchCommand.cs b/src/Cli/dotnet/Commands/Package/Search/PackageSearchCommand.cs
index bedb88c51c1e..eaa2c5989da9 100644
--- a/src/Cli/dotnet/Commands/Package/Search/PackageSearchCommand.cs
+++ b/src/Cli/dotnet/Commands/Package/Search/PackageSearchCommand.cs
@@ -10,7 +10,7 @@ namespace Microsoft.DotNet.Cli.Commands.Package.Search;
internal sealed class PackageSearchCommand(ParseResult parseResult)
: CommandBase(parseResult)
{
- public override int Execute()
+ public override int Execute(CancellationToken cancellationToken)
{
var args = new List
{
@@ -25,6 +25,6 @@ public override int Execute()
}
args.AddRange(_parseResult.OptionValuesToBeForwarded(Definition));
- return NuGetCommand.Run([.. args]);
+ return NuGetCommand.Run([.. args], cancellationToken);
}
}
diff --git a/src/Cli/dotnet/Commands/Project/Convert/ProjectConvertCommand.cs b/src/Cli/dotnet/Commands/Project/Convert/ProjectConvertCommand.cs
index 95530742f329..8871903bda9c 100644
--- a/src/Cli/dotnet/Commands/Project/Convert/ProjectConvertCommand.cs
+++ b/src/Cli/dotnet/Commands/Project/Convert/ProjectConvertCommand.cs
@@ -36,10 +36,12 @@ public ProjectConvertCommand(ParseResult parseResult)
_interactive = parseResult.GetValue(Definition.InteractiveOption);
}
- public override int Execute() => ExecuteAsync().AsTask().GetAwaiter().GetResult();
+ public override int Execute(CancellationToken cancellationToken) => ExecuteAsync(cancellationToken).AsTask().GetAwaiter().GetResult();
- public async ValueTask ExecuteAsync()
+ public async ValueTask ExecuteAsync(CancellationToken cancellationToken)
{
+ cancellationToken.ThrowIfCancellationRequested();
+
// Check the entry point file path.
string file = Path.GetFullPath(_file);
if (!VirtualProjectBuilder.IsValidEntryPointPath(file))
diff --git a/src/Cli/dotnet/Commands/Project/ProjectCommandParser.cs b/src/Cli/dotnet/Commands/Project/ProjectCommandParser.cs
index b4ba64b24b27..eb0067bc6391 100644
--- a/src/Cli/dotnet/Commands/Project/ProjectCommandParser.cs
+++ b/src/Cli/dotnet/Commands/Project/ProjectCommandParser.cs
@@ -2,6 +2,7 @@
// The .NET Foundation licenses this file to you under the MIT license.
using System.Diagnostics.CodeAnalysis;
+using Microsoft.DotNet.Cli.CommandLine;
using Microsoft.DotNet.Cli.Commands.Project.Convert;
using Microsoft.DotNet.Cli.Extensions;
@@ -13,6 +14,6 @@ internal sealed class ProjectCommandParser
public static void ConfigureCommand(ProjectCommandDefinition command)
{
command.SetAction(parseResult => parseResult.HandleMissingCommand());
- command.ConvertCommand.SetAction(parseResult => new ProjectConvertCommand(parseResult).Execute());
+ command.ConvertCommand.SetAction((parseResult, cancellationToken) => new ProjectConvertCommand(parseResult).Execute(cancellationToken));
}
}
diff --git a/src/Cli/dotnet/Commands/Publish/PublishCommand.cs b/src/Cli/dotnet/Commands/Publish/PublishCommand.cs
index 0dc35f71eab9..0c60202e0cbc 100644
--- a/src/Cli/dotnet/Commands/Publish/PublishCommand.cs
+++ b/src/Cli/dotnet/Commands/Publish/PublishCommand.cs
@@ -22,13 +22,19 @@ private PublishCommand(
{
}
- public static CommandBase FromArgs(string[] args, string? msbuildPath = null)
+ public static CommandBase FromArgs(
+ string[] args,
+ CancellationToken cancellationToken,
+ string? msbuildPath = null)
{
var parseResult = Parser.Parse(["dotnet", "publish", .. args]);
- return FromParseResult(parseResult);
+ return FromParseResult(parseResult, cancellationToken, msbuildPath);
}
- public static CommandBase FromParseResult(ParseResult parseResult, string? msbuildPath = null)
+ public static CommandBase FromParseResult(
+ ParseResult parseResult,
+ CancellationToken cancellationToken,
+ string? msbuildPath = null)
{
var definition = (PublishCommandDefinition)parseResult.CommandResult.Command;
@@ -75,17 +81,21 @@ public static CommandBase FromParseResult(ParseResult parseResult, string? msbui
parseResult.HasOption(definition.ConfigurationOption) ? parseResult.GetValue(definition.ConfigurationOption) : null,
parseResult.HasOption(definition.FrameworkOption) ? parseResult.GetValue(definition.FrameworkOption) : null
);
- var projectLocator = new ReleasePropertyProjectLocator(msbuildArgs.GlobalProperties, MSBuildPropertyNames.PUBLISH_RELEASE, options);
+ var projectLocator = new ReleasePropertyProjectLocator(
+ msbuildArgs.GlobalProperties,
+ MSBuildPropertyNames.PUBLISH_RELEASE,
+ options,
+ cancellationToken);
var releaseModeProperties = projectLocator.GetCustomDefaultConfigurationValueIfSpecified();
return msbuildArgs.CloneWithAdditionalProperties(releaseModeProperties);
}
);
}
- public static int Run(ParseResult parseResult)
+ public static int Run(ParseResult parseResult, CancellationToken cancellationToken)
{
parseResult.HandleDebugSwitch();
- return FromParseResult(parseResult).Execute();
+ return FromParseResult(parseResult, cancellationToken).Execute(cancellationToken);
}
}
diff --git a/src/Cli/dotnet/Commands/Reference/Add/ReferenceAddCommand.cs b/src/Cli/dotnet/Commands/Reference/Add/ReferenceAddCommand.cs
index 129d29663aeb..6cb9d70c9eba 100644
--- a/src/Cli/dotnet/Commands/Reference/Add/ReferenceAddCommand.cs
+++ b/src/Cli/dotnet/Commands/Reference/Add/ReferenceAddCommand.cs
@@ -28,7 +28,7 @@ public ReferenceAddCommand(ParseResult parseResult)
parseResult);
}
- public override int Execute()
+ public override int Execute(CancellationToken cancellationToken)
{
using var projects = new ProjectCollection();
bool interactive = _parseResult.GetValue(Definition.InteractiveOption);
diff --git a/src/Cli/dotnet/Commands/Reference/List/ReferenceListCommand.cs b/src/Cli/dotnet/Commands/Reference/List/ReferenceListCommand.cs
index 3988eb7314d1..0c0735bb8c2b 100644
--- a/src/Cli/dotnet/Commands/Reference/List/ReferenceListCommand.cs
+++ b/src/Cli/dotnet/Commands/Reference/List/ReferenceListCommand.cs
@@ -30,7 +30,7 @@ public ReferenceListCommand(ParseResult parseResult)
parseResult);
}
- public override int Execute()
+ public override int Execute(CancellationToken cancellationToken)
{
if (_allowedAppKinds.HasFlag(AppKinds.FileBased) && VirtualProjectBuilder.IsValidEntryPointPath(_fileOrDirectory))
{
diff --git a/src/Cli/dotnet/Commands/Reference/ReferenceCommandParser.cs b/src/Cli/dotnet/Commands/Reference/ReferenceCommandParser.cs
index eccd1f478e17..7b3c858f4f09 100644
--- a/src/Cli/dotnet/Commands/Reference/ReferenceCommandParser.cs
+++ b/src/Cli/dotnet/Commands/Reference/ReferenceCommandParser.cs
@@ -17,15 +17,15 @@ public static void ConfigureCommand(ReferenceCommandDefinition command)
{
command.SetAction(parseResult => parseResult.HandleMissingCommand());
- command.AddCommand.SetAction(parseResult => new ReferenceAddCommand(parseResult).Execute());
+ command.AddCommand.SetAction((parseResult, cancellationToken) => new ReferenceAddCommand(parseResult).Execute(cancellationToken));
command.AddCommand.FrameworkOption.AddCompletions(CliCompletion.TargetFrameworksFromProjectFile);
- command.ListCommand.SetAction(parseResult => new ReferenceListCommand(parseResult).Execute());
+ command.ListCommand.SetAction((parseResult, cancellationToken) => new ReferenceListCommand(parseResult).Execute(cancellationToken));
var projectPathArgument = command.RemoveCommand.ProjectPathArgument;
projectPathArgument.CompletionSources.Add(CliCompletion.ProjectReferencesFromProjectFile);
projectPathArgument.IsDynamic = true;
- command.RemoveCommand.SetAction(parseResult => new ReferenceRemoveCommand(parseResult).Execute());
+ command.RemoveCommand.SetAction((parseResult, cancellationToken) => new ReferenceRemoveCommand(parseResult).Execute(cancellationToken));
}
}
diff --git a/src/Cli/dotnet/Commands/Reference/Remove/ReferenceRemoveCommand.cs b/src/Cli/dotnet/Commands/Reference/Remove/ReferenceRemoveCommand.cs
index c4fa44b06551..d550238c8321 100644
--- a/src/Cli/dotnet/Commands/Reference/Remove/ReferenceRemoveCommand.cs
+++ b/src/Cli/dotnet/Commands/Reference/Remove/ReferenceRemoveCommand.cs
@@ -34,7 +34,7 @@ public ReferenceRemoveCommand(ParseResult parseResult)
}
}
- public override int Execute()
+ public override int Execute(CancellationToken cancellationToken)
{
if (_allowedAppKinds.HasFlag(AppKinds.FileBased) && VirtualProjectBuilder.IsValidEntryPointPath(_fileOrDirectory))
{
diff --git a/src/Cli/dotnet/Commands/Restore/RestoreCommand.cs b/src/Cli/dotnet/Commands/Restore/RestoreCommand.cs
index 8f2e96fb3f91..5fad4338b62d 100644
--- a/src/Cli/dotnet/Commands/Restore/RestoreCommand.cs
+++ b/src/Cli/dotnet/Commands/Restore/RestoreCommand.cs
@@ -62,17 +62,17 @@ public static MSBuildForwardingApp CreateForwarding(MSBuildArgs msbuildArgs, str
return forwardingApp;
}
- public static int Run(string[] args)
+ public static int Run(string[] args, CancellationToken cancellationToken)
{
DebugHelper.HandleDebugSwitch(ref args);
- return FromArgs(args).Execute();
+ return FromArgs(args).Execute(cancellationToken);
}
- public static int Run(ParseResult parseResult)
+ public static int Run(ParseResult parseResult, CancellationToken cancellationToken)
{
parseResult.HandleDebugSwitch();
- return FromParseResult(parseResult).Execute();
+ return FromParseResult(parseResult).Execute(cancellationToken);
}
}
diff --git a/src/Cli/dotnet/Commands/Restore/RestoringCommand.cs b/src/Cli/dotnet/Commands/Restore/RestoringCommand.cs
index eb69124622ed..8527f629150d 100644
--- a/src/Cli/dotnet/Commands/Restore/RestoringCommand.cs
+++ b/src/Cli/dotnet/Commands/Restore/RestoringCommand.cs
@@ -31,6 +31,8 @@ public class RestoringCommand : MSBuildForwardingApp
public MSBuildForwardingApp? SeparateRestoreCommand { get; }
private readonly bool AdvertiseWorkloadUpdates;
+ private readonly string _userProfileDir;
+ private readonly string _workingDirectory;
public RestoringCommand(
MSBuildArgs msbuildArgs,
@@ -51,8 +53,8 @@ internal RestoringCommand(
string workingDirectory)
: base(GetCommandArguments(msbuildArgs, noRestore), msbuildPath)
{
- userProfileDir = CliFolderPathCalculator.DotnetUserProfileFolderPath;
- Task.Run(() => WorkloadManifestUpdater.BackgroundUpdateAdvertisingManifestsAsync(userProfileDir, workingDirectory));
+ _userProfileDir = userProfileDir ?? CliFolderPathCalculator.DotnetUserProfileFolderPath;
+ _workingDirectory = workingDirectory;
SdkVulnerabilityNotifier.BackgroundUpdateCacheIfNeeded();
SeparateRestoreCommand = GetSeparateRestoreCommand(msbuildArgs, noRestore, msbuildPath);
AdvertiseWorkloadUpdates = advertiseWorkloadUpdates ?? msbuildArgs.OtherMSBuildArgs.All(arg => FlagsThatTriggerSilentRestore.All(f => !arg.Contains(f, StringComparison.OrdinalIgnoreCase)));
@@ -238,18 +240,22 @@ private static bool IsExcludedFromSeparateRestore(string argument)
private static bool TriggersSilentSeparateRestore(string argument)
=> FlagsThatTriggerSilentSeparateRestore.Any(p => argument.StartsWith(p, StringComparison.OrdinalIgnoreCase));
- public override int Execute() => Execute(workingDirectory: null);
+ public override int Execute(CancellationToken cancellationToken) => Execute(workingDirectory: null, cancellationToken);
- internal override int ExecuteOutOfProc(string workingDirectory) => Execute(workingDirectory);
+ internal override int ExecuteOutOfProc(string workingDirectory, CancellationToken cancellationToken) => Execute(workingDirectory, cancellationToken);
- private int Execute(string? workingDirectory)
+ private int Execute(string? workingDirectory, CancellationToken cancellationToken)
{
+ _ = Task.Run(
+ () => WorkloadManifestUpdater.BackgroundUpdateAdvertisingManifestsAsync(_userProfileDir, _workingDirectory, cancellationToken),
+ cancellationToken);
+
int exitCode;
if (SeparateRestoreCommand != null)
{
exitCode = workingDirectory is null
- ? SeparateRestoreCommand.Execute()
- : SeparateRestoreCommand.ExecuteOutOfProc(workingDirectory);
+ ? SeparateRestoreCommand.Execute(cancellationToken)
+ : SeparateRestoreCommand.ExecuteOutOfProc(workingDirectory, cancellationToken);
if (exitCode != 0)
{
return exitCode;
@@ -257,8 +263,8 @@ private int Execute(string? workingDirectory)
}
exitCode = workingDirectory is null
- ? base.Execute()
- : base.ExecuteOutOfProc(workingDirectory);
+ ? base.Execute(cancellationToken)
+ : base.ExecuteOutOfProc(workingDirectory, cancellationToken);
if (AdvertiseWorkloadUpdates)
{
WorkloadManifestUpdater.AdvertiseWorkloadUpdates();
diff --git a/src/Cli/dotnet/Commands/Run/AotRunCommand.cs b/src/Cli/dotnet/Commands/Run/AotRunCommand.cs
index a317dd7be817..60849a602c74 100644
--- a/src/Cli/dotnet/Commands/Run/AotRunCommand.cs
+++ b/src/Cli/dotnet/Commands/Run/AotRunCommand.cs
@@ -27,21 +27,23 @@ internal static class AotRunCommand
///
/// The shared run command definition.
internal static void ConfigureCommand(RunCommandDefinition command)
- => command.SetAction(parseResult => Execute(parseResult, Launch));
+ => command.SetAction((parseResult, cancellationToken) => Execute(parseResult, cancellationToken));
///
/// Executes an eligible file-based application through the Native AOT launcher.
///
/// The parsed run invocation.
+ /// Token observed while launching the invocation.
/// The launched process exit code.
- internal static int Execute(ParseResult parseResult)
- => Execute(parseResult, Launch);
+ internal static int Execute(ParseResult parseResult, CancellationToken cancellationToken)
+ => Execute(parseResult, invocation => Launch(invocation, cancellationToken), cancellationToken);
///
/// Plans and executes an eligible file-based application using an injected launcher.
///
/// The parsed run invocation.
/// Launches the committed invocation.
+ /// Token observed while launching the invocation.
/// The current directory used for discovery and relative paths.
/// The launcher exit code.
/// The invocation cannot be handled safely by the Native AOT path.
@@ -49,8 +51,10 @@ internal static int Execute(ParseResult parseResult)
internal static int Execute(
ParseResult parseResult,
Func launch,
+ CancellationToken cancellationToken,
string? currentDirectory = null)
{
+ cancellationToken.ThrowIfCancellationRequested();
currentDirectory ??= Environment.CurrentDirectory;
var definition = (RunCommandDefinition)parseResult.CommandResult.Command;
if (!TryGetEligibleInvocationInputs(
@@ -193,12 +197,14 @@ internal static int Execute(
FileBasedAppRunPlan.MarkArtifactsPathUsed(artifactsPath);
}
+ cancellationToken.ThrowIfCancellationRequested();
int exitCode = launch(new AotRunInvocation(
command,
commandArguments,
launchEnvironment,
workingDirectory,
artifactsPath));
+ cancellationToken.ThrowIfCancellationRequested();
return exitCode;
}
@@ -228,7 +234,7 @@ private static void EnsureLaunchProfileDoesNotRequireMSBuild(
}
}
- private static int Launch(AotRunInvocation invocation)
+ private static int Launch(AotRunInvocation invocation, CancellationToken cancellationToken)
{
var commandSpec = new CommandSpec(
invocation.Command,
@@ -244,7 +250,7 @@ private static int Launch(AotRunInvocation invocation)
Console.CancelKeyPress += cancelHandler;
try
{
- return command.Execute().ExitCode;
+ return command.Execute(cancellationToken).ExitCode;
}
finally
{
diff --git a/src/Cli/dotnet/Commands/Run/Api/RunApiCommand.cs b/src/Cli/dotnet/Commands/Run/Api/RunApiCommand.cs
index 4cfd783a4fe0..8d95026a0aea 100644
--- a/src/Cli/dotnet/Commands/Run/Api/RunApiCommand.cs
+++ b/src/Cli/dotnet/Commands/Run/Api/RunApiCommand.cs
@@ -20,26 +20,43 @@ namespace Microsoft.DotNet.Cli.Commands.Run.Api;
[RequiresDynamicCode("Uses MSBuild Object Model types, which are not AOT-safe")]
internal sealed class RunApiCommand(ParseResult parseResult) : CommandBase(parseResult)
{
- public override int Execute()
+ public override int Execute(CancellationToken cancellationToken) =>
+ ExecuteAsync(cancellationToken).GetAwaiter().GetResult();
+
+ internal async Task ExecuteAsync(CancellationToken cancellationToken)
{
- for (string? line; (line = Console.ReadLine()) != null;)
+ try
{
- if (string.IsNullOrWhiteSpace(line))
- {
- continue;
- }
-
- try
+ using var inputHandle = Console.OpenStandardInputHandle();
+ using Stream inputStream = inputHandle.IsInvalid ? Stream.Null : new FileStream(inputHandle, FileAccess.Read);
+ using var inputReader = new StreamReader(inputStream, Console.InputEncoding, detectEncodingFromByteOrderMarks: false);
+ // Unix FileStream cancellation cannot interrupt a read already blocked in the OS.
+ for (string? line; (line = await inputReader.ReadLineAsync(cancellationToken).AsTask()
+ .WaitAsync(cancellationToken).ConfigureAwait(false)) != null;)
{
- RunApiInput input = JsonSerializer.Deserialize(line, RunFileApiJsonSerializerContext.Default.RunApiInput)!;
- RunApiOutput output = input.Execute();
- Respond(output);
- }
- catch (Exception ex)
- {
- Respond(new RunApiOutput.Error { Message = ex.Message, Details = ex.ToString() });
+ if (string.IsNullOrWhiteSpace(line))
+ {
+ continue;
+ }
+
+ try
+ {
+ RunApiInput input = JsonSerializer.Deserialize(line, RunFileApiJsonSerializerContext.Default.RunApiInput)!;
+ RunApiOutput output = input.Execute();
+ Respond(output);
+ }
+ catch (Exception ex)
+ {
+ Respond(new RunApiOutput.Error { Message = ex.Message, Details = ex.ToString() });
+ }
}
}
+ catch (OperationCanceledException) when (
+ cancellationToken.IsCancellationRequested &&
+ !ProcessLifecycle.IsSignalTerminationRequested)
+ {
+ // A standalone caller cancelled the stdin read; exit the loop gracefully.
+ }
return 0;
diff --git a/src/Cli/dotnet/Commands/Run/Api/RunApiCommandParser.cs b/src/Cli/dotnet/Commands/Run/Api/RunApiCommandParser.cs
index 2c4225bea076..7f9d43248b73 100644
--- a/src/Cli/dotnet/Commands/Run/Api/RunApiCommandParser.cs
+++ b/src/Cli/dotnet/Commands/Run/Api/RunApiCommandParser.cs
@@ -3,6 +3,7 @@
using System.CommandLine;
using System.Diagnostics.CodeAnalysis;
+using Microsoft.DotNet.Cli.CommandLine;
namespace Microsoft.DotNet.Cli.Commands.Run.Api;
@@ -11,6 +12,6 @@ internal sealed class RunApiCommandParser
[RequiresDynamicCode("Uses MSBuild Object Model types, which are not AOT-safe")]
public static void ConfigureCommand(RunApiCommandDefinition command)
{
- command.SetAction(parseResult => new RunApiCommand(parseResult).Execute());
+ command.SetAction((parseResult, cancellationToken) => new RunApiCommand(parseResult).Execute(cancellationToken));
}
}
diff --git a/src/Cli/dotnet/Commands/Run/CSharpCompilerCommand.cs b/src/Cli/dotnet/Commands/Run/CSharpCompilerCommand.cs
index 168a5ddbfb7e..272d647179ac 100644
--- a/src/Cli/dotnet/Commands/Run/CSharpCompilerCommand.cs
+++ b/src/Cli/dotnet/Commands/Run/CSharpCompilerCommand.cs
@@ -77,8 +77,10 @@ private partial class CSharpCompilerCommandJsonSerializerContext : JsonSerialize
///
/// Whether the returned error code should not cause the build to fail but instead fallback to full MSBuild.
///
- public int Execute(out bool fallbackToNormalBuild)
+ public int Execute(CancellationToken cancellationToken, out bool fallbackToNormalBuild)
{
+ cancellationToken.ThrowIfCancellationRequested();
+
// Write .rsp file and other intermediate build outputs.
PrepareAuxiliaryFiles(out string rspPath);
@@ -120,12 +122,13 @@ public int Execute(out bool fallbackToNormalBuild)
clientDirectory: ClientDirectory,
buildEnvironment: StandardBuildEnvironment.Instance,
logger,
- cancellationToken: default);
+ cancellationToken);
// Process the response.
- var exitCode = ProcessBuildResponse(responseTask.Result, out fallbackToNormalBuild);
+ var exitCode = ProcessBuildResponse(responseTask.GetAwaiter().GetResult(), out fallbackToNormalBuild);
// Copy from obj to bin only if the build succeeded.
+ cancellationToken.ThrowIfCancellationRequested();
if (exitCode == 0 &&
BuildResultFile != null &&
CSharpCommandLineParser.Default.Parse(CscArguments, BaseDirectory, sdkDirectory: null) is { OutputFileName: { } outputFileName } parsedArgs)
diff --git a/src/Cli/dotnet/Commands/Run/RunCommand.cs b/src/Cli/dotnet/Commands/Run/RunCommand.cs
index 392a7cf906fd..1f1f756578e0 100644
--- a/src/Cli/dotnet/Commands/Run/RunCommand.cs
+++ b/src/Cli/dotnet/Commands/Run/RunCommand.cs
@@ -141,7 +141,7 @@ public RunCommand(
EnvironmentVariables = environmentVariables;
}
- public int Execute()
+ public int Execute(CancellationToken cancellationToken)
{
// Create a single logger for all MSBuild operations (device selection + build/run)
// File-based runs (.cs files) don't support device selection and should use the existing logger behavior
@@ -198,7 +198,8 @@ public int Execute()
out projectBuilder,
selector?.IntermediateOutputPath,
selector?.HasRuntimeEnvironmentVariableSupport ?? false,
- requiresProjectExpansion);
+ requiresProjectExpansion,
+ cancellationToken);
runPropertiesFromEvaluation = projectBuilder?.LastBuild.Level == BuildLevel.All;
}
else if (EntryPointFileFullPath is not null && launchProfileParseResult.Profile is not ExecutableLaunchProfile)
@@ -245,7 +246,7 @@ public int Execute()
// Ignore Ctrl-C for the remainder of the command's execution
Console.CancelKeyPress += (sender, e) => { e.Cancel = true; };
- return targetCommand.Execute().ExitCode;
+ return targetCommand.Execute(cancellationToken).ExitCode;
}
catch (InvalidProjectFileException e)
{
@@ -518,13 +519,14 @@ private void EnsureProjectIsBuilt(
out VirtualProjectBuildingCommand? projectBuilder,
string? intermediateOutputPath,
bool hasRuntimeEnvironmentVariableSupport,
- bool requiresProjectExpansion)
+ bool requiresProjectExpansion,
+ CancellationToken cancellationToken)
{
int buildResult;
if (EntryPointFileFullPath is not null)
{
projectBuilder = CreateProjectBuilder();
- buildResult = projectBuilder.Execute();
+ buildResult = projectBuilder.Execute(cancellationToken);
projectFactory = requiresProjectExpansion || !CanUseRunPropertiesForCscBuiltProgram(projectBuilder.LastBuild.Level, projectBuilder.LastBuild.Cache?.PreviousEntry)
? projectBuilder.CreateProjectInstance
: null;
@@ -552,7 +554,7 @@ private void EnsureProjectIsBuilt(
buildArgs,
NoRestore || _restoreDoneForDeviceSelection,
advertiseWorkloadUpdates: false
- ).Execute();
+ ).Execute(cancellationToken);
}
finally
{
@@ -1075,11 +1077,11 @@ bool UsingRunCommandShorthandProjectOption(ParseResult parseResult)
}
}
- public static int Run(ParseResult parseResult)
+ public static int Run(ParseResult parseResult, CancellationToken cancellationToken)
{
parseResult.HandleDebugSwitch();
- return FromParseResult(parseResult).Execute();
+ return FromParseResult(parseResult).Execute(cancellationToken);
}
public static ParseResult ModifyParseResultForShorthandProjectOption(ParseResult parseResult)
diff --git a/src/Cli/dotnet/Commands/Run/VirtualProjectBuildingCommand.cs b/src/Cli/dotnet/Commands/Run/VirtualProjectBuildingCommand.cs
index ae43fca9600a..b3c4d5348c06 100644
--- a/src/Cli/dotnet/Commands/Run/VirtualProjectBuildingCommand.cs
+++ b/src/Cli/dotnet/Commands/Run/VirtualProjectBuildingCommand.cs
@@ -13,6 +13,7 @@
using Microsoft.Build.Logging.SimpleErrorLogger;
using Microsoft.CodeAnalysis;
using Microsoft.DotNet.Cli.Commands.Clean.FileBasedAppArtifacts;
+using Microsoft.DotNet.Cli.Commands.MSBuild;
using Microsoft.DotNet.Cli.Commands.Restore;
using Microsoft.DotNet.Cli.Utils;
using Microsoft.DotNet.Cli.Utils.Extensions;
@@ -106,8 +107,10 @@ public VirtualProjectBuildingCommand(
#if !CLI_AOT
[UnconditionalSuppressMessage("AOT", "IL2026", Justification = "Temporary unblock for dotnet/msbuild#14064 (MSBuild build APIs are now [RequiresUnreferencedCode]). dotnet CLI runs MSBuild in-proc (not trimmed). Remove when dotnet/sdk#55225 is fixed.")]
[UnconditionalSuppressMessage("AOT", "IL3050", Justification ="In non-AOT mode we have MSBuild available, so using types from it is safe.")]
- public override int Execute()
+ public override int Execute(CancellationToken cancellationToken)
{
+ cancellationToken.ThrowIfCancellationRequested();
+
bool msbuildGet = MSBuildArgs.GetProperty is [_, ..] || MSBuildArgs.GetItem is [_, ..] || MSBuildArgs.GetTargetResult is [_, ..];
bool evalOnly = msbuildGet && Builder.RequestedTargets is null or [];
bool minimizeStdOut = msbuildGet && MSBuildArgs.GetResultOutputFile is null or [];
@@ -175,7 +178,7 @@ public override int Execute()
CscArguments = cache.PreviousEntry?.CscArguments ?? [],
BuildResultFile = cache.PreviousEntry?.BuildResultFile,
}
- .Execute(out bool fallbackToNormalBuild);
+ .Execute(cancellationToken, out bool fallbackToNormalBuild);
if (!fallbackToNormalBuild)
{
@@ -210,7 +213,10 @@ public override int Execute()
CleanFileBasedAppArtifactsCommand.StartAutomaticCleanupIfNeeded();
}
+ using IDisposable softCancellationTimeout =
+ ProcessLifecycle.OverrideSoftCancellationTimeout(MSBuildForwardingApp.BuildSoftCancellationTimeout);
IDisposable? environmentScope = null;
+ bool buildStarted = false;
try
{
Dictionary additionalEnvironmentVariables = [];
@@ -243,6 +249,10 @@ public override int Execute()
};
BuildManager.DefaultBuildManager.BeginBuild(parameters);
+ buildStarted = true;
+ using CancellationTokenRegistration cancellationRegistration = cancellationToken.Register(
+ static () => BuildManager.DefaultBuildManager.CancelAllSubmissions());
+ cancellationToken.ThrowIfCancellationRequested();
int exitCode = 0;
ProjectInstance? projectInstance = null;
@@ -254,7 +264,10 @@ public override int Execute()
if (!NoRestore && !evalOnly)
{
var restoreRequest = new BuildRequestData(
- CreateProjectInstance(projectCollection, additionalGlobalProperties: GetAdditionalRestoreGlobalProperties(MSBuildArgs.RestoreGlobalProperties)),
+ CreateProjectInstance(
+ projectCollection,
+ additionalGlobalProperties: GetAdditionalRestoreGlobalProperties(MSBuildArgs.RestoreGlobalProperties),
+ cancellationToken),
targetsToBuild: ["Restore"],
hostServices: null,
// We don't include ClearCachesAfterBuild flag unlike MSBuild's implicit restore
@@ -263,6 +276,7 @@ public override int Execute()
BuildRequestDataFlags.SkipNonexistentTargets | BuildRequestDataFlags.IgnoreMissingEmptyAndInvalidImports | BuildRequestDataFlags.FailOnUnresolvedSdk);
var restoreResult = BuildManager.DefaultBuildManager.BuildRequest(restoreRequest);
+ cancellationToken.ThrowIfCancellationRequested();
if (restoreResult.OverallResult != BuildResultCode.Success)
{
exitCode = 1;
@@ -279,13 +293,14 @@ public override int Execute()
? requestedTargets
: [Constants.Build, Constants.CoreCompile];
var buildRequest = new BuildRequestData(
- CreateProjectInstance(projectCollection),
+ CreateProjectInstance(projectCollection, additionalGlobalProperties: null, cancellationToken),
targetsToBuild: effectiveTargets,
hostServices: null,
// SkipNonexistentTargets: CoreCompile doesn't exist in the outer build of multi-target projects.
BuildRequestDataFlags.SkipNonexistentTargets);
var buildResult = BuildManager.DefaultBuildManager.BuildRequest(buildRequest);
+ cancellationToken.ThrowIfCancellationRequested();
if (buildResult.OverallResult != BuildResultCode.Success)
{
exitCode = 1;
@@ -306,7 +321,7 @@ public override int Execute()
CacheCscArguments(cache, buildResult);
WriteCscRsp(cache);
- CollectAdditionalSources(cache, buildRequest.ProjectInstance);
+ CollectAdditionalSources(cache, buildRequest.ProjectInstance, cancellationToken);
CollectBuildOutputs(cache, buildRequest.ProjectInstance);
MarkBuildSuccess(cache);
@@ -320,16 +335,13 @@ public override int Execute()
// Print build information.
if (msbuildGet)
{
- projectInstance ??= CreateProjectInstance(projectCollection);
- PrintBuildInformation(projectCollection, projectInstance, buildOrRestoreResult);
+ projectInstance ??= CreateProjectInstance(projectCollection, additionalGlobalProperties: null, cancellationToken);
+ PrintBuildInformation(projectCollection, projectInstance, buildOrRestoreResult, cancellationToken);
}
- BuildManager.DefaultBuildManager.EndBuild();
- consoleLogger = null; // avoid double disposal which would throw
-
return exitCode;
}
- catch (Exception e)
+ catch (Exception e) when (e is not OperationCanceledException)
{
Reporter.Error.WriteLine(CommandLoggingContext.IsVerbose ?
e.ToString().Red().Bold() :
@@ -338,6 +350,12 @@ public override int Execute()
}
finally
{
+ if (buildStarted)
+ {
+ BuildManager.DefaultBuildManager.EndBuild();
+ consoleLogger = null; // avoid double disposal which would throw
+ }
+
environmentScope?.Dispose();
if (binaryLogger?.IsValueCreated == true) binaryLogger.Value.ReallyShutdown();
consoleLogger?.Shutdown();
@@ -517,16 +535,20 @@ bool CanSaveCache(ProjectInstance projectInstance)
}
[RequiresDynamicCode("Uses MSBuild Object Model types, which are not AOT-safe")]
- void CollectAdditionalSources(FileBasedAppCacheInfo cache, ProjectInstance projectInstance)
+ void CollectAdditionalSources(FileBasedAppCacheInfo cache, ProjectInstance projectInstance, CancellationToken cancellationToken)
{
Debug.Assert(cache.CurrentEntry.AdditionalSources.Count == 0);
+ cancellationToken.ThrowIfCancellationRequested();
var entryPointFileDirectory = Path.GetDirectoryName(Builder.EntryPointFileFullPath);
Debug.Assert(entryPointFileDirectory != null);
var mapping = Builder.GetItemMappingAsync(projectInstance.Wrap(), ErrorReporters.IgnoringReporter).AsTask().GetAwaiter().GetResult();
+ cancellationToken.ThrowIfCancellationRequested();
foreach (var entry in mapping)
{
+ cancellationToken.ThrowIfCancellationRequested();
+
if (string.Equals(entry.ItemType, "None", StringComparison.OrdinalIgnoreCase))
{
continue;
@@ -545,8 +567,13 @@ void CollectAdditionalSources(FileBasedAppCacheInfo cache, ProjectInstance proje
cache.CurrentEntry.AdditionalSources.Remove(RunFileBuildCacheEntry.AdditionalSource.Create(Builder.EntryPointFileFullPath));
}
- void PrintBuildInformation(ProjectCollection projectCollection, ProjectInstance projectInstance, BuildResult? buildOrRestoreResult)
+ void PrintBuildInformation(
+ ProjectCollection projectCollection,
+ ProjectInstance projectInstance,
+ BuildResult? buildOrRestoreResult,
+ CancellationToken cancellationToken)
{
+ cancellationToken.ThrowIfCancellationRequested();
var resultOutputFile = MSBuildArgs.GetResultOutputFile is [{ } file, ..] ? file : null;
// If a single property is requested, don't print as JSON.
@@ -577,6 +604,7 @@ void PrintBuildInformation(ProjectCollection projectCollection, ProjectInstance
foreach (var propertyName in MSBuildArgs.GetProperty)
{
+ cancellationToken.ThrowIfCancellationRequested();
writer.WriteString(propertyName, projectInstance.GetPropertyValue(propertyName));
}
@@ -590,6 +618,7 @@ void PrintBuildInformation(ProjectCollection projectCollection, ProjectInstance
foreach (var itemName in MSBuildArgs.GetItem)
{
+ cancellationToken.ThrowIfCancellationRequested();
writer.WritePropertyName(itemName);
writer.WriteStartArray();
@@ -626,6 +655,7 @@ void PrintBuildInformation(ProjectCollection projectCollection, ProjectInstance
foreach (var targetName in MSBuildArgs.GetTargetResult)
{
+ cancellationToken.ThrowIfCancellationRequested();
var targetResult = buildOrRestoreResult.ResultsByTarget[targetName];
writer.WritePropertyName(targetName);
@@ -795,12 +825,28 @@ private void MarkBuildSuccess(FileBasedAppCacheInfo cache)
[RequiresDynamicCode("Uses MSBuild Object Model types, which are not AOT-safe")]
public ProjectInstance CreateProjectInstance(ProjectCollection projectCollection)
{
- return CreateProjectInstance(projectCollection, additionalGlobalProperties: null);
+ return CreateProjectInstance(
+ projectCollection,
+ additionalGlobalProperties: null,
+ ProcessLifecycle.CancellationToken);
}
[RequiresDynamicCode("Uses MSBuild Object Model types, which are not AOT-safe")]
public ProjectInstance CreateProjectInstance(ProjectCollection projectCollection, IDictionary? additionalGlobalProperties = null)
{
+ return CreateProjectInstance(
+ projectCollection,
+ additionalGlobalProperties,
+ ProcessLifecycle.CancellationToken);
+ }
+
+ [RequiresDynamicCode("Uses MSBuild Object Model types, which are not AOT-safe")]
+ private ProjectInstance CreateProjectInstance(
+ ProjectCollection projectCollection,
+ IDictionary? additionalGlobalProperties,
+ CancellationToken cancellationToken)
+ {
+ cancellationToken.ThrowIfCancellationRequested();
var projectCollectionWrapped = projectCollection.Wrap();
var result = Builder.CreateProjectInstanceAsync(
@@ -808,6 +854,7 @@ public ProjectInstance CreateProjectInstance(ProjectCollection projectCollection
ThrowingReporter,
Directives,
additionalGlobalProperties).AsTask().GetAwaiter().GetResult();
+ cancellationToken.ThrowIfCancellationRequested();
EvaluatedDirectives = result.EvaluatedDirectives;
diff --git a/src/Cli/dotnet/Commands/Sdk/Check/BundleOutputWriter.cs b/src/Cli/dotnet/Commands/Sdk/Check/BundleOutputWriter.cs
index ef6afb5592ec..2d6a64042893 100644
--- a/src/Cli/dotnet/Commands/Sdk/Check/BundleOutputWriter.cs
+++ b/src/Cli/dotnet/Commands/Sdk/Check/BundleOutputWriter.cs
@@ -12,7 +12,8 @@ namespace Microsoft.DotNet.Cli.Commands.Sdk.Check;
internal class BundleOutputWriter(
ProductCollection productCollection,
IProductCollectionProvider productCollectionProvider,
- IReporter reporter)
+ IReporter reporter,
+ CancellationToken cancellationToken)
{
protected ProductCollection _productCollection = productCollection;
@@ -20,6 +21,8 @@ internal class BundleOutputWriter(
protected readonly IReporter _reporter = reporter;
+ protected readonly CancellationToken _cancellationToken = cancellationToken;
+
protected bool? BundleIsMaintenance(INetBundleInfo bundle)
{
return _productCollection
diff --git a/src/Cli/dotnet/Commands/Sdk/Check/IProductCollectionProvider.cs b/src/Cli/dotnet/Commands/Sdk/Check/IProductCollectionProvider.cs
index 2effbab2e20e..a58baba3a675 100644
--- a/src/Cli/dotnet/Commands/Sdk/Check/IProductCollectionProvider.cs
+++ b/src/Cli/dotnet/Commands/Sdk/Check/IProductCollectionProvider.cs
@@ -9,7 +9,7 @@ namespace Microsoft.DotNet.Cli.Commands.Sdk.Check;
public interface IProductCollectionProvider
{
- ProductCollection GetProductCollection(Uri uri = null, string filePath = null);
+ ProductCollection GetProductCollection(CancellationToken cancellationToken, Uri uri = null, string filePath = null);
- IEnumerable GetProductReleases(Product product);
+ IEnumerable GetProductReleases(Product product, CancellationToken cancellationToken);
}
diff --git a/src/Cli/dotnet/Commands/Sdk/Check/ProductCollectionProvider.cs b/src/Cli/dotnet/Commands/Sdk/Check/ProductCollectionProvider.cs
index 0c3ff39c8940..b44cba0618a6 100644
--- a/src/Cli/dotnet/Commands/Sdk/Check/ProductCollectionProvider.cs
+++ b/src/Cli/dotnet/Commands/Sdk/Check/ProductCollectionProvider.cs
@@ -10,31 +10,41 @@ namespace Microsoft.DotNet.Cli.Commands.Sdk.Check;
public class ProductCollectionProvider : IProductCollectionProvider
{
- public ProductCollection GetProductCollection(Uri uri = null, string filePath = null)
+ public ProductCollection GetProductCollection(
+ CancellationToken cancellationToken,
+ Uri uri = null,
+ string filePath = null)
{
try
{
- return uri != null ? Task.Run(() => ProductCollection.GetAsync(uri.ToString())).Result :
- filePath != null ? Task.Run(() => ProductCollection.GetFromFileAsync(filePath, false)).Result :
- Task.Run(() => ProductCollection.GetAsync()).Result;
+ cancellationToken.ThrowIfCancellationRequested();
+ Task productCollection = uri != null
+ ? ProductCollection.GetAsync(uri.ToString())
+ : filePath != null
+ ? ProductCollection.GetFromFileAsync(filePath, false)
+ : ProductCollection.GetAsync();
+
+ return productCollection.WaitAsync(cancellationToken).GetAwaiter().GetResult();
}
- catch (Exception e)
+ catch (Exception e) when (e is not OperationCanceledException)
{
throw new GracefulException(string.Format(CliCommandStrings.ReleasesLibraryFailed, e.Message));
}
}
- public IEnumerable GetProductReleases(Deployment.DotNet.Releases.Product product)
+ public IEnumerable GetProductReleases(
+ Deployment.DotNet.Releases.Product product,
+ CancellationToken cancellationToken)
{
try
{
- return product.GetReleasesAsync().Result;
+ cancellationToken.ThrowIfCancellationRequested();
+ return product.GetReleasesAsync()
+ .WaitAsync(cancellationToken)
+ .GetAwaiter()
+ .GetResult();
}
- catch (Exception ex) when (ex is HttpRequestException ||
- ex is FileNotFoundException ||
- ex is AggregateException aggregateEx &&
- (aggregateEx.InnerException is HttpRequestException ||
- aggregateEx.InnerException is FileNotFoundException))
+ catch (Exception ex) when (ex is HttpRequestException || ex is FileNotFoundException)
{
// Return empty collection if releases are not available (e.g., unreleased preview versions)
// This handles cases where the releases.json file doesn't exist yet for a version
diff --git a/src/Cli/dotnet/Commands/Sdk/Check/RuntimeOutputWriter.cs b/src/Cli/dotnet/Commands/Sdk/Check/RuntimeOutputWriter.cs
index 0746c9ada5e1..327e0901dee7 100644
--- a/src/Cli/dotnet/Commands/Sdk/Check/RuntimeOutputWriter.cs
+++ b/src/Cli/dotnet/Commands/Sdk/Check/RuntimeOutputWriter.cs
@@ -11,7 +11,8 @@ internal class RuntimeOutputWriter(
IEnumerable runtimeInfo,
ProductCollection productCollection,
IProductCollectionProvider productCollectionProvider,
- IReporter reporter) : BundleOutputWriter(productCollection, productCollectionProvider, reporter)
+ IReporter reporter,
+ CancellationToken cancellationToken) : BundleOutputWriter(productCollection, productCollectionProvider, reporter, cancellationToken)
{
private readonly IEnumerable _runtimeInfo = runtimeInfo;
diff --git a/src/Cli/dotnet/Commands/Sdk/Check/SdkCheckCommand.cs b/src/Cli/dotnet/Commands/Sdk/Check/SdkCheckCommand.cs
index 695f77b61ebc..a9b2ec8d0910 100644
--- a/src/Cli/dotnet/Commands/Sdk/Check/SdkCheckCommand.cs
+++ b/src/Cli/dotnet/Commands/Sdk/Check/SdkCheckCommand.cs
@@ -38,7 +38,7 @@ public SdkCheckCommand(
_productCollectionProvider = productCollectionProvider == null ? new ProductCollectionProvider() : productCollectionProvider;
}
- public override int Execute()
+ public override int Execute(CancellationToken cancellationToken)
{
if (_sdkCheckConfig != null && !string.IsNullOrEmpty(_sdkCheckConfig.CommandOutputReplacementString))
{
@@ -48,14 +48,16 @@ public override int Execute()
}
else
{
+ cancellationToken.ThrowIfCancellationRequested();
try
{
var productCollection = _productCollectionProvider.GetProductCollection(
+ cancellationToken,
_sdkCheckConfig?.ReleasesUri == null ? null : new Uri(_sdkCheckConfig.ReleasesUri),
_sdkCheckConfig?.ReleasesFilePath == null ? null : _sdkCheckConfig.ReleasesFilePath);
var environmentInfo = _netBundleProvider.GetDotnetEnvironmentInfo(_dotnetPath);
- var sdkFormatter = new SdkOutputWriter(environmentInfo.SdkInfo, productCollection, _productCollectionProvider, _reporter);
- var runtimeFormatter = new RuntimeOutputWriter(environmentInfo.RuntimeInfo, productCollection, _productCollectionProvider, _reporter);
+ var sdkFormatter = new SdkOutputWriter(environmentInfo.SdkInfo, productCollection, _productCollectionProvider, _reporter, cancellationToken);
+ var runtimeFormatter = new RuntimeOutputWriter(environmentInfo.RuntimeInfo, productCollection, _productCollectionProvider, _reporter, cancellationToken);
sdkFormatter.PrintSdkInfo();
_reporter.WriteLine();
@@ -80,12 +82,12 @@ public override int Execute()
return 0;
}
- public static int Run(ParseResult parseResult)
+ public static int Run(ParseResult parseResult, CancellationToken cancellationToken)
{
#if CLI_AOT
- return new SdkCheckCommand(parseResult, dotnetRoot: NativeEntryPoint.DotnetRoot).Execute();
+ return new SdkCheckCommand(parseResult, dotnetRoot: NativeEntryPoint.DotnetRoot).Execute(cancellationToken);
#else
- return new SdkCheckCommand(parseResult).Execute();
+ return new SdkCheckCommand(parseResult).Execute(cancellationToken);
#endif
}
}
diff --git a/src/Cli/dotnet/Commands/Sdk/Check/SdkOutputWriter.cs b/src/Cli/dotnet/Commands/Sdk/Check/SdkOutputWriter.cs
index 0ee9e8b5d225..dfb42409bae0 100644
--- a/src/Cli/dotnet/Commands/Sdk/Check/SdkOutputWriter.cs
+++ b/src/Cli/dotnet/Commands/Sdk/Check/SdkOutputWriter.cs
@@ -11,7 +11,8 @@ internal class SdkOutputWriter(
IEnumerable sdkInfo,
ProductCollection productCollection,
IProductCollectionProvider productCollectionProvider,
- IReporter reporter) : BundleOutputWriter(productCollection, productCollectionProvider, reporter)
+ IReporter reporter,
+ CancellationToken cancellationToken) : BundleOutputWriter(productCollection, productCollectionProvider, reporter, cancellationToken)
{
private readonly IEnumerable _sdkInfo = sdkInfo;
@@ -83,7 +84,7 @@ private bool NewerSdkPatchExists(NetSdkInfo bundle)
else
{
// Fetch detailed product release information
- var productReleases = _productCollectionProvider.GetProductReleases(product);
+ var productReleases = _productCollectionProvider.GetProductReleases(product, _cancellationToken);
var featureBandVersions = productReleases
.SelectMany(release => release.Sdks)
.Select(sdk => sdk.Version)
diff --git a/src/Cli/dotnet/Commands/Sdk/SdkCommandParser.cs b/src/Cli/dotnet/Commands/Sdk/SdkCommandParser.cs
index 71e308437dba..f6bd8fd9aedd 100644
--- a/src/Cli/dotnet/Commands/Sdk/SdkCommandParser.cs
+++ b/src/Cli/dotnet/Commands/Sdk/SdkCommandParser.cs
@@ -3,6 +3,7 @@
using System.CommandLine;
using Microsoft.DotNet.Cli.Commands.Sdk.Check;
+using Microsoft.DotNet.Cli.CommandLine;
using Microsoft.DotNet.Cli.Extensions;
namespace Microsoft.DotNet.Cli.Commands.Sdk;
diff --git a/src/Cli/dotnet/Commands/Solution/Add/SolutionAddCommand.cs b/src/Cli/dotnet/Commands/Solution/Add/SolutionAddCommand.cs
index 9f5a17f45de1..7b7d555a1c8e 100644
--- a/src/Cli/dotnet/Commands/Solution/Add/SolutionAddCommand.cs
+++ b/src/Cli/dotnet/Commands/Solution/Add/SolutionAddCommand.cs
@@ -51,7 +51,7 @@ public SolutionAddCommand(ParseResult parseResult)
_solutionFileFullPath = SlnFileFactory.GetSolutionFileFullPath(_fileOrDirectory, includeSolutionFilterFiles: true);
}
- public override int Execute()
+ public override int Execute(CancellationToken cancellationToken)
{
if (_projects.Count == 0)
{
@@ -70,12 +70,12 @@ public override int Execute()
// Check if we're working with a solution filter file
if (_solutionFileFullPath.HasExtension(SlnfFileHelper.SlnfExtension))
{
- AddProjectsToSolutionFilter(fullProjectPaths);
+ AddProjectsToSolutionFilter(fullProjectPaths, cancellationToken);
}
else
{
// Add projects to the solution
- AddProjectsToSolutionAsync(fullProjectPaths, CancellationToken.None).GetAwaiter().GetResult();
+ AddProjectsToSolutionAsync(fullProjectPaths, cancellationToken).GetAwaiter().GetResult();
}
return 0;
}
@@ -128,7 +128,7 @@ public override int Execute()
private async Task AddProjectsToSolutionAsync(IEnumerable projectPaths, CancellationToken cancellationToken)
{
- SolutionModel solution = SlnFileFactory.CreateFromFileOrDirectory(_solutionFileFullPath);
+ SolutionModel solution = SlnFileFactory.CreateFromFileOrDirectory(_solutionFileFullPath, cancellationToken);
Debug.Assert(solution.SerializerExtension is not null);
ISolutionSerializer serializer = solution.SerializerExtension.Serializer;
@@ -280,7 +280,9 @@ static bool IsInSameFolderHierarchy(SolutionItemModel? projectParent, SolutionFo
}
}
- private void AddProjectsToSolutionFilter(IEnumerable projectPaths)
+ private void AddProjectsToSolutionFilter(
+ IEnumerable projectPaths,
+ CancellationToken cancellationToken)
{
// Solution filter files don't support --in-root or --solution-folder options
if (_inRoot || !string.IsNullOrEmpty(_solutionFolderPath))
@@ -289,11 +291,11 @@ private void AddProjectsToSolutionFilter(IEnumerable projectPaths)
}
// Load the filtered solution to get the parent solution path and existing projects
- SolutionModel filteredSolution = SlnFileFactory.CreateFromFilteredSolutionFile(_solutionFileFullPath);
+ SolutionModel filteredSolution = SlnFileFactory.CreateFromFilteredSolutionFile(_solutionFileFullPath, cancellationToken);
string parentSolutionPath = filteredSolution.Description!; // The parent solution path is stored in Description
// Load the parent solution to validate projects exist in it
- SolutionModel parentSolution = SlnFileFactory.CreateFromFileOrDirectory(parentSolutionPath);
+ SolutionModel parentSolution = SlnFileFactory.CreateFromFileOrDirectory(parentSolutionPath, cancellationToken);
// Get existing projects in the filter (already normalized to OS separator by CreateFromFilteredSolutionFile)
var existingProjects = filteredSolution.SolutionProjects.Select(p => p.FilePath).ToHashSet();
diff --git a/src/Cli/dotnet/Commands/Solution/List/SolutionListCommand.cs b/src/Cli/dotnet/Commands/Solution/List/SolutionListCommand.cs
index 4026d1afa86b..0d1025ecc78e 100644
--- a/src/Cli/dotnet/Commands/Solution/List/SolutionListCommand.cs
+++ b/src/Cli/dotnet/Commands/Solution/List/SolutionListCommand.cs
@@ -21,23 +21,23 @@ public SolutionListCommand(ParseResult parseResult)
_displaySolutionFolders = parseResult.GetValue(Definition.SolutionFolderOption);
}
- public override int Execute()
+ public override int Execute(CancellationToken cancellationToken)
{
string solutionFileFullPath = SlnFileFactory.GetSolutionFileFullPath(_fileOrDirectory, includeSolutionFilterFiles: true);
try
{
- ListAllProjectsAsync(solutionFileFullPath);
+ ListAllProjects(solutionFileFullPath, cancellationToken);
return 0;
}
- catch (Exception ex)
+ catch (Exception ex) when (ex is not OperationCanceledException)
{
throw new GracefulException(CliStrings.InvalidSolutionFormatString, solutionFileFullPath, ex.Message);
}
}
- private void ListAllProjectsAsync(string solutionFileFullPath)
+ private void ListAllProjects(string solutionFileFullPath, CancellationToken cancellationToken)
{
- SolutionModel solution = SlnFileFactory.CreateFromFileOrDirectory(solutionFileFullPath);
+ SolutionModel solution = SlnFileFactory.CreateFromFileOrDirectory(solutionFileFullPath, cancellationToken);
string[] paths;
if (_displaySolutionFolders)
{
diff --git a/src/Cli/dotnet/Commands/Solution/Migrate/SolutionMigrateCommand.cs b/src/Cli/dotnet/Commands/Solution/Migrate/SolutionMigrateCommand.cs
index 47ef19bdf6dc..8781bb3b4b01 100644
--- a/src/Cli/dotnet/Commands/Solution/Migrate/SolutionMigrateCommand.cs
+++ b/src/Cli/dotnet/Commands/Solution/Migrate/SolutionMigrateCommand.cs
@@ -23,7 +23,7 @@ public SolutionMigrateCommand(ParseResult parseResult, IReporter reporter = null
}
- public override int Execute()
+ public override int Execute(CancellationToken cancellationToken)
{
string slnFileFullPath = SlnFileFactory.GetSolutionFileFullPath(_slnFileOrDirectory);
if (slnFileFullPath.HasExtension(".slnx"))
@@ -33,10 +33,10 @@ public override int Execute()
string slnxFileFullPath = Path.ChangeExtension(slnFileFullPath, "slnx");
try
{
- ConvertToSlnxAsync(slnFileFullPath, slnxFileFullPath, CancellationToken.None).Wait();
+ ConvertToSlnxAsync(slnFileFullPath, slnxFileFullPath, cancellationToken).GetAwaiter().GetResult();
return 0;
}
- catch (Exception ex)
+ catch (Exception ex) when (ex is not OperationCanceledException)
{
throw new GracefulException(ex.Message, ex);
}
@@ -44,7 +44,7 @@ public override int Execute()
private async Task ConvertToSlnxAsync(string filePath, string slnxFilePath, CancellationToken cancellationToken)
{
- SolutionModel solution = SlnFileFactory.CreateFromFileOrDirectory(filePath);
+ SolutionModel solution = SlnFileFactory.CreateFromFileOrDirectory(filePath, cancellationToken);
await SolutionSerializers.SlnXml.SaveAsync(slnxFilePath, solution, cancellationToken);
_reporter.WriteLine(CliCommandStrings.SlnxGenerated, slnxFilePath);
}
diff --git a/src/Cli/dotnet/Commands/Solution/Remove/SolutionRemoveCommand.cs b/src/Cli/dotnet/Commands/Solution/Remove/SolutionRemoveCommand.cs
index 8e18861ec3ac..4d48da867b84 100644
--- a/src/Cli/dotnet/Commands/Solution/Remove/SolutionRemoveCommand.cs
+++ b/src/Cli/dotnet/Commands/Solution/Remove/SolutionRemoveCommand.cs
@@ -25,7 +25,7 @@ public SolutionRemoveCommand(ParseResult parseResult)
SolutionArgumentValidator.ParseAndValidateArguments(_fileOrDirectory, _projects, SolutionArgumentValidator.CommandType.Remove);
}
- public override int Execute()
+ public override int Execute(CancellationToken cancellationToken)
{
string solutionFileFullPath = SlnFileFactory.GetSolutionFileFullPath(_fileOrDirectory, includeSolutionFilterFiles: true);
if (_projects.Count == 0)
@@ -46,15 +46,15 @@ public override int Execute()
// Check if we're working with a solution filter file
if (solutionFileFullPath.HasExtension(SlnfFileHelper.SlnfExtension))
{
- RemoveProjectsFromSolutionFilter(solutionFileFullPath, relativeProjectPaths);
+ RemoveProjectsFromSolutionFilter(solutionFileFullPath, relativeProjectPaths, cancellationToken);
}
else
{
- RemoveProjectsAsync(solutionFileFullPath, relativeProjectPaths, CancellationToken.None).GetAwaiter().GetResult();
+ RemoveProjectsAsync(solutionFileFullPath, relativeProjectPaths, cancellationToken).GetAwaiter().GetResult();
}
return 0;
}
- catch (Exception ex) when (ex is not GracefulException)
+ catch (Exception ex) when (ex is not GracefulException and not OperationCanceledException)
{
if (ex is SolutionException || ex.InnerException is SolutionException)
{
@@ -66,7 +66,7 @@ public override int Execute()
private static async Task RemoveProjectsAsync(string solutionFileFullPath, IEnumerable projectPaths, CancellationToken cancellationToken)
{
- SolutionModel solution = SlnFileFactory.CreateFromFileOrDirectory(solutionFileFullPath);
+ SolutionModel solution = SlnFileFactory.CreateFromFileOrDirectory(solutionFileFullPath, cancellationToken);
ISolutionSerializer serializer = solution.SerializerExtension.Serializer;
// set UTF-8 BOM encoding for .sln
@@ -139,10 +139,13 @@ private static async Task RemoveProjectsAsync(string solutionFileFullPath, IEnum
await serializer.SaveAsync(solutionFileFullPath, solution, cancellationToken);
}
- private static void RemoveProjectsFromSolutionFilter(string slnfFileFullPath, IEnumerable projectPaths)
+ private static void RemoveProjectsFromSolutionFilter(
+ string slnfFileFullPath,
+ IEnumerable projectPaths,
+ CancellationToken cancellationToken)
{
// Load the filtered solution to get the parent solution path and existing projects
- SolutionModel filteredSolution = SlnFileFactory.CreateFromFilteredSolutionFile(slnfFileFullPath);
+ SolutionModel filteredSolution = SlnFileFactory.CreateFromFilteredSolutionFile(slnfFileFullPath, cancellationToken);
string parentSolutionPath = filteredSolution.Description!; // The parent solution path is stored in Description
// Get existing projects in the filter
diff --git a/src/Cli/dotnet/Commands/Solution/SolutionCommandParser.cs b/src/Cli/dotnet/Commands/Solution/SolutionCommandParser.cs
index 64c9fd3b840f..782aa67aa8a3 100644
--- a/src/Cli/dotnet/Commands/Solution/SolutionCommandParser.cs
+++ b/src/Cli/dotnet/Commands/Solution/SolutionCommandParser.cs
@@ -2,6 +2,7 @@
// The .NET Foundation licenses this file to you under the MIT license.
using System.CommandLine;
+using Microsoft.DotNet.Cli.CommandLine;
using Microsoft.DotNet.Cli.Extensions;
#if !CLI_AOT
using Microsoft.DotNet.Cli.Commands.Solution.Add;
@@ -21,10 +22,10 @@ public static void ConfigureCommand(SolutionCommandDefinition command)
// 'sln add' requires MSBuild, so it falls back to the managed CLI.
command.AddCommand.SetAction((Func)(_ => throw new CommandNotAvailableInAotException()));
#else
- command.AddCommand.SetAction(parseResult => new SolutionAddCommand(parseResult).Execute());
+ command.AddCommand.SetAction((parseResult, cancellationToken) => new SolutionAddCommand(parseResult).Execute(cancellationToken));
#endif
- command.ListCommand.SetAction(parseResult => new SolutionListCommand(parseResult).Execute());
- command.MigrateCommand.SetAction(parseResult => new SolutionMigrateCommand(parseResult).Execute());
- command.RemoveCommand.SetAction(parseResult => new SolutionRemoveCommand(parseResult).Execute());
+ command.ListCommand.SetAction((parseResult, cancellationToken) => new SolutionListCommand(parseResult).Execute(cancellationToken));
+ command.MigrateCommand.SetAction((parseResult, cancellationToken) => new SolutionMigrateCommand(parseResult).Execute(cancellationToken));
+ command.RemoveCommand.SetAction((parseResult, cancellationToken) => new SolutionRemoveCommand(parseResult).Execute(cancellationToken));
}
}
diff --git a/src/Cli/dotnet/Commands/Test/MTP/CtrlCCancellationManager.cs b/src/Cli/dotnet/Commands/Test/MTP/CtrlCCancellationManager.cs
index c2d10c0ed96e..89b2cbd8335a 100644
--- a/src/Cli/dotnet/Commands/Test/MTP/CtrlCCancellationManager.cs
+++ b/src/Cli/dotnet/Commands/Test/MTP/CtrlCCancellationManager.cs
@@ -1,24 +1,26 @@
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
-using System.Collections.Concurrent;
using System.Diagnostics;
using Microsoft.DotNet.Cli.Utils;
namespace Microsoft.DotNet.Cli.Commands.Test;
///
-/// Mirrors the two-stage Ctrl+C cancellation UX implemented in Microsoft.Testing.Platform
+/// Mirrors the two-stage cancellation UX implemented in Microsoft.Testing.Platform
/// (testfx PR #8581 / SDK issue https://github.com/dotnet/sdk/issues/50732) at the
-/// dotnet test orchestrator level:
+/// dotnet test orchestrator level. It can observe either console Ctrl+C directly
+/// or the shared CLI lifecycle's cooperative and forceful cancellation tokens:
///
/// - First Ctrl+C: cooperative cancellation. The is signaled so the
/// queue stops scheduling new test apps; running test apps are left alone so they can
/// gracefully report their final state via IPC (their own testfx-side Ctrl+C handler will
/// cancel the session inside the child process).
-/// - Second Ctrl+C: force exit. Every registered child process is killed
-/// (entireProcessTree: true) and the host process exits with
-/// (=3).
+/// - Forceful cancellation: SIGTERM is forwarded to every registered child with a
+/// bounded grace period, while a repeated Ctrl+C kills every registered process tree
+/// immediately. When this manager owns the console handler, a second Ctrl+C also exits
+/// with (=3); otherwise the shared process
+/// lifecycle owns the host exit.
/// - Any further presses are no-ops (the state machine is idempotent).
///
///
@@ -31,12 +33,21 @@ internal sealed class CtrlCCancellationManager : IDisposable
private readonly CancellationTokenSource _cancellationTokenSource = new();
private readonly Action _onFirstCtrlC;
private readonly Action _exitAction;
- private readonly ConcurrentDictionary _processes = new();
+ private readonly Lock _processesLock = new();
+ private readonly HashSet _processes = [];
private readonly bool _subscribedToConsole;
+ private readonly CancellationTokenRegistration _cooperativeCancellationRegistration;
+ private readonly CancellationTokenRegistration _forcefulCancellationRegistration;
private int _state = StateIdle;
+ private int _forwardSigTerm;
private int _disposed;
- public CtrlCCancellationManager(Action onFirstCtrlC, Action? exitAction = null, bool subscribeToConsole = true)
+ public CtrlCCancellationManager(
+ Action onFirstCtrlC,
+ Action? exitAction = null,
+ bool subscribeToConsole = true,
+ CancellationToken cooperativeCancellationToken = default,
+ CancellationToken forcefulCancellationToken = default)
{
_onFirstCtrlC = onFirstCtrlC ?? throw new ArgumentNullException(nameof(onFirstCtrlC));
_exitAction = exitAction ?? Environment.Exit;
@@ -46,6 +57,12 @@ public CtrlCCancellationManager(Action onFirstCtrlC, Action? exitAction = n
Console.CancelKeyPress += OnConsoleCancelKeyPress;
_subscribedToConsole = true;
}
+
+ _cooperativeCancellationRegistration =
+ cooperativeCancellationToken.Register(() => HandleCooperativeCancellation());
+ _forcefulCancellationRegistration =
+ forcefulCancellationToken.Register(
+ () => HandleForcefulCancellation(ProcessLifecycle.IsSigTermRequested));
}
///
@@ -56,20 +73,28 @@ public CtrlCCancellationManager(Action onFirstCtrlC, Action? exitAction = n
public CancellationToken Token => _cancellationTokenSource.Token;
///
- /// Registers a child test-app process so it will be killed if the user requests a force exit
- /// (second Ctrl+C). If the manager is already in the forcing state when this is called, the
- /// process is killed immediately to avoid orphaning a child that started during the force
- /// exit race window.
+ /// Starts and registers a child test-app process as one operation with respect to forceful
+ /// cancellation. Returns without starting a process when forceful
+ /// cancellation has already begun.
///
- public void Register(Process process)
+ public Process? StartAndRegister(Func startProcess)
{
- ArgumentNullException.ThrowIfNull(process);
-
- _processes.TryAdd(process, 0);
+ ArgumentNullException.ThrowIfNull(startProcess);
- if (Volatile.Read(ref _state) == StateForcing)
+ lock (_processesLock)
{
- TryKill(process);
+ if (Volatile.Read(ref _state) == StateForcing)
+ {
+ return null;
+ }
+
+ Process? process = startProcess();
+ if (process is not null)
+ {
+ _processes.Add(process);
+ }
+
+ return process;
}
}
@@ -77,7 +102,10 @@ public void Unregister(Process process)
{
ArgumentNullException.ThrowIfNull(process);
- _processes.TryRemove(process, out _);
+ lock (_processesLock)
+ {
+ _processes.Remove(process);
+ }
}
///
@@ -85,6 +113,8 @@ public void Unregister(Process process)
///
internal void SimulateCtrlC() => HandleCtrlC();
+ internal bool IsForcing => Volatile.Read(ref _state) == StateForcing;
+
private void OnConsoleCancelKeyPress(object? sender, ConsoleCancelEventArgs e)
{
// Suppress the runtime's default Ctrl+C handling on every press, including the second one,
@@ -96,48 +126,87 @@ private void OnConsoleCancelKeyPress(object? sender, ConsoleCancelEventArgs e)
}
private void HandleCtrlC()
+ {
+ if (HandleCooperativeCancellation())
+ {
+ return;
+ }
+
+ if (HandleForcefulCancellation(forwardSigTerm: false))
+ {
+ _exitAction(ExitCode.TestSessionAborted);
+ }
+ }
+
+ private bool HandleCooperativeCancellation()
{
// First press: Idle -> Cancelling. Signal the token, invoke the UI callback.
- if (Interlocked.CompareExchange(ref _state, StateCancelling, StateIdle) == StateIdle)
+ if (Interlocked.CompareExchange(ref _state, StateCancelling, StateIdle) != StateIdle)
{
- // CancellationTokenSource.Cancel() can throw an AggregateException if any registered
- // callback throws, or an ObjectDisposedException if Dispose races with a Ctrl+C press
- // (e.g. user presses Ctrl+C while we're tearing down). Swallow both — we still want the
- // state machine to advance and the UI callback to run.
- try
- {
- _cancellationTokenSource.Cancel();
- }
- catch (Exception ex) when (ex is AggregateException or ObjectDisposedException)
- {
- Logger.LogTrace($"Exception during CtrlCCancellationManager cancel:\n{ex}");
- }
+ return false;
+ }
- // The UI callback (typically TerminalTestReporter.StartCancelling) must not be able to
- // affect cancellation state — wrap it best-effort.
- try
- {
- _onFirstCtrlC();
- }
- catch (Exception ex)
- {
- Logger.LogTrace($"Exception during CtrlCCancellationManager first-press UI callback:\n{ex}");
- }
+ // CancellationTokenSource.Cancel() can throw an AggregateException if any registered
+ // callback throws, or an ObjectDisposedException if Dispose races with a Ctrl+C press
+ // (e.g. user presses Ctrl+C while we're tearing down). Swallow both — we still want the
+ // state machine to advance and the UI callback to run.
+ try
+ {
+ _cancellationTokenSource.Cancel();
+ }
+ catch (Exception ex) when (ex is AggregateException or ObjectDisposedException)
+ {
+ Logger.LogTrace($"Exception during CtrlCCancellationManager cancel:\n{ex}");
+ }
- return;
+ // The UI callback (typically TerminalTestReporter.StartCancelling) must not be able to
+ // affect cancellation state — wrap it best-effort.
+ try
+ {
+ _onFirstCtrlC();
+ }
+ catch (Exception ex)
+ {
+ Logger.LogTrace($"Exception during CtrlCCancellationManager first-press UI callback:\n{ex}");
}
- // Second press: Cancelling -> Forcing. Kill every registered child and exit.
- // We intentionally do not print any additional message here because the user already saw
- // the "Press Ctrl+C again to force exit." hint and the exit itself is the confirmation.
- if (Interlocked.CompareExchange(ref _state, StateForcing, StateCancelling) == StateCancelling)
+ return true;
+ }
+
+ private bool HandleForcefulCancellation(bool forwardSigTerm)
+ {
+ // A second Ctrl+C transitions Cancelling -> Forcing. A forceful lifecycle signal such as
+ // SIGTERM can transition directly from Idle -> Forcing.
+ if (forwardSigTerm)
{
- foreach (var process in _processes.Keys)
- {
- TryKill(process);
- }
+ Volatile.Write(ref _forwardSigTerm, 1);
+ }
- _exitAction(ExitCode.TestSessionAborted);
+ int previousState = Interlocked.Exchange(ref _state, StateForcing);
+ if (previousState == StateForcing)
+ {
+ return false;
+ }
+
+ lock (_processesLock)
+ {
+ TerminateProcesses([.. _processes], forwardSigTerm);
+ }
+
+ return true;
+ }
+
+ private static void TerminateProcesses(IReadOnlyCollection processes, bool forwardSigTerm)
+ {
+ if (forwardSigTerm)
+ {
+ ProcessReaper.ForwardSigTermAndTerminate(processes);
+ return;
+ }
+
+ foreach (Process process in processes)
+ {
+ TryKill(process);
}
}
@@ -170,6 +239,8 @@ public void Dispose()
Console.CancelKeyPress -= OnConsoleCancelKeyPress;
}
+ _cooperativeCancellationRegistration.Dispose();
+ _forcefulCancellationRegistration.Dispose();
_cancellationTokenSource.Dispose();
}
}
diff --git a/src/Cli/dotnet/Commands/Test/MTP/ITestHandler.cs b/src/Cli/dotnet/Commands/Test/MTP/ITestHandler.cs
index 78a4db7ac3d5..3cfd5bfc27e7 100644
--- a/src/Cli/dotnet/Commands/Test/MTP/ITestHandler.cs
+++ b/src/Cli/dotnet/Commands/Test/MTP/ITestHandler.cs
@@ -5,7 +5,7 @@ namespace Microsoft.DotNet.Cli.Commands.Test;
internal interface ITestHandler
{
- bool Initialize();
+ bool Initialize(CancellationToken cancellationToken);
///
/// All modules that will be run. Available after a successful so the
diff --git a/src/Cli/dotnet/Commands/Test/MTP/MSBuildHandler.cs b/src/Cli/dotnet/Commands/Test/MTP/MSBuildHandler.cs
index bdc23fecf473..b87c2c7b389e 100644
--- a/src/Cli/dotnet/Commands/Test/MTP/MSBuildHandler.cs
+++ b/src/Cli/dotnet/Commands/Test/MTP/MSBuildHandler.cs
@@ -17,7 +17,7 @@ internal sealed class MSBuildHandler(BuildOptions buildOptions, MSBuildSession b
private readonly ConcurrentBag _testApplications = [];
- public bool Initialize()
+ public bool Initialize(CancellationToken cancellationToken)
{
PathOptions pathOptions = _buildOptions.PathOptions;
@@ -27,8 +27,8 @@ public bool Initialize()
}
(IEnumerable projects, int buildExitCode) = isSolution ?
- MSBuildUtility.GetProjectsFromSolution(projectOrSolutionFilePath, _buildOptions, _buildSession) :
- MSBuildUtility.GetProjectsFromProject(projectOrSolutionFilePath, _buildOptions, _buildSession);
+ MSBuildUtility.GetProjectsFromSolution(projectOrSolutionFilePath, _buildOptions, _buildSession, cancellationToken) :
+ MSBuildUtility.GetProjectsFromProject(projectOrSolutionFilePath, _buildOptions, _buildSession, cancellationToken);
LogProjectProperties(projects);
diff --git a/src/Cli/dotnet/Commands/Test/MTP/MSBuildUtility.cs b/src/Cli/dotnet/Commands/Test/MTP/MSBuildUtility.cs
index 53c65c7d5809..ba3262e0bd73 100644
--- a/src/Cli/dotnet/Commands/Test/MTP/MSBuildUtility.cs
+++ b/src/Cli/dotnet/Commands/Test/MTP/MSBuildUtility.cs
@@ -31,12 +31,13 @@ internal static class MSBuildUtility
public static (IEnumerable Projects, int BuildExitCode) GetProjectsFromSolution(
string solutionFilePath,
BuildOptions buildOptions,
- MSBuildSession buildSession)
+ MSBuildSession buildSession,
+ CancellationToken cancellationToken)
{
using var _ = MSBuildForwardingAppWithoutLogging.SetMSBuildRequiredEnvironmentVariables();
solutionFilePath = Path.GetFullPath(solutionFilePath, buildSession.WorkingDirectory);
- int buildExitCode = BuildOrRestoreProjectOrSolution(solutionFilePath, buildOptions, buildSession);
+ int buildExitCode = BuildOrRestoreProjectOrSolution(solutionFilePath, buildOptions, buildSession, cancellationToken);
if (buildExitCode != 0)
{
@@ -75,7 +76,7 @@ public static (IEnumerable Projects, int BuildExitCode) GetProjectsFromProject(
string projectFilePath,
BuildOptions buildOptions,
- MSBuildSession buildSession)
+ MSBuildSession buildSession,
+ CancellationToken cancellationToken)
{
using var _ = MSBuildForwardingAppWithoutLogging.SetMSBuildRequiredEnvironmentVariables();
@@ -106,10 +108,10 @@ public static (IEnumerable(), exitCode);
@@ -397,7 +400,11 @@ private static (string? PositionalProjectOrSolution, string? PositionalTestModul
}
[RequiresDynamicCode("Uses MSBuild Object Model types, which are not AOT-safe")]
- private static int BuildOrRestoreProjectOrSolution(string filePath, BuildOptions buildOptions, MSBuildSession buildSession)
+ private static int BuildOrRestoreProjectOrSolution(
+ string filePath,
+ BuildOptions buildOptions,
+ MSBuildSession buildSession,
+ CancellationToken cancellationToken)
{
if (buildOptions.HasNoBuild)
{
@@ -454,8 +461,8 @@ private static int BuildOrRestoreProjectOrSolution(string filePath, BuildOptions
workingDirectory: buildSession.WorkingDirectory);
return buildSession.RequiresOutOfProcessBuild
- ? command.ExecuteOutOfProc(buildSession.WorkingDirectory)
- : command.Execute();
+ ? command.ExecuteOutOfProc(buildSession.WorkingDirectory, cancellationToken)
+ : command.Execute(cancellationToken);
}
finally
{
@@ -470,7 +477,8 @@ private static (ConcurrentBag projects,
BuildOptions buildOptions,
IReadOnlyDictionary globalProperties,
- MSBuildSession buildSession)
+ MSBuildSession buildSession,
+ CancellationToken cancellationToken)
{
var allProjects = new ConcurrentBag();
var solutionProjects = projects.ToArray();
@@ -564,6 +572,7 @@ private static (ConcurrentBag> CustomHelpLayout()
WriteHelpOptions(context);
Console.WriteLine(CliCommandStrings.HelpWaitingForOptionsAndExtensions);
- Run(context.ParseResult, isHelp: true);
+ // This help-rendering path is invoked synchronously from System.CommandLine's HelpBuilder
+ // override, so use the process-wide token that tracks Ctrl+C and process shutdown.
+ Run(context.ParseResult, isHelp: true, Utils.ProcessLifecycle.CancellationToken);
if (_commandLineOptionNameToModuleNames.IsEmpty)
{
diff --git a/src/Cli/dotnet/Commands/Test/MTP/MicrosoftTestingPlatformTestCommand.cs b/src/Cli/dotnet/Commands/Test/MTP/MicrosoftTestingPlatformTestCommand.cs
index d8c7758af641..fd7c7c5ab93b 100644
--- a/src/Cli/dotnet/Commands/Test/MTP/MicrosoftTestingPlatformTestCommand.cs
+++ b/src/Cli/dotnet/Commands/Test/MTP/MicrosoftTestingPlatformTestCommand.cs
@@ -29,7 +29,7 @@ internal partial class MicrosoftTestingPlatformTestCommand
private const string ZeroTestsPolicyOptionName = "--zero-tests-policy";
private const string ZeroTestsPolicyStrictArgument = "strict";
- public int Run(ParseResult parseResult, bool isHelp)
+ public int Run(ParseResult parseResult, bool isHelp, CancellationToken cancellationToken)
{
var definition = (TestCommandDefinition.MicrosoftTestingPlatform)parseResult.CommandResult.Command;
string invocationWorkingDirectory = Directory.GetCurrentDirectory();
@@ -113,7 +113,7 @@ public int Run(ParseResult parseResult, bool isHelp)
: RuntimeFeature.IsDynamicCodeSupported ? new MSBuildHandler(buildOptions, buildSession)
: throw new PlatformNotSupportedException("Dynamic code is not supported on this platform.");
- if (!testHandler.Initialize())
+ if (!testHandler.Initialize(cancellationToken))
{
return ExitCode.GenericFailure;
}
@@ -176,7 +176,16 @@ public int Run(ParseResult parseResult, bool isHelp)
: parseResult.GetValue(definition.TimeoutOption),
onCancellation: _ => output.MarkCancelled());
- using var ctrlC = new CtrlCCancellationManager(output.StartCancelling);
+ using IDisposable? lifecycleCancellationTimeout = ProcessLifecycle.IsInitialized
+ ? ProcessLifecycle.OverrideSoftCancellationTimeout(Timeout.InfiniteTimeSpan)
+ : null;
+ using var ctrlC = new CtrlCCancellationManager(
+ output.StartCancelling,
+ subscribeToConsole: !ProcessLifecycle.IsInitialized,
+ cooperativeCancellationToken: cancellationToken,
+ forcefulCancellationToken: ProcessLifecycle.IsInitialized
+ ? ProcessLifecycle.ForcefulCancellationToken
+ : default);
using var queueCancellation = CancellationTokenSource.CreateLinkedTokenSource(ctrlC.Token, testRunPolicy.Token);
var artifactPostProcessingManager = new ArtifactPostProcessingManager();
int? exitCode = null;
@@ -247,14 +256,22 @@ public int Run(ParseResult parseResult, bool isHelp)
}
exitCode = actionQueue.ApplyExitCodeIgnorePolicy(exitCode.Value);
+ cancellationToken.ThrowIfCancellationRequested();
return exitCode.Value;
}
finally
{
- output.TestExecutionCompleted(DateTimeOffset.Now, exitCode);
+ output.TestExecutionCompleted(
+ DateTimeOffset.Now,
+ GetExitCodeForReporting(exitCode, cancellationToken.IsCancellationRequested));
}
}
+ internal static int? GetExitCodeForReporting(int? exitCode, bool cancellationRequested)
+ => cancellationRequested && exitCode == ExitCode.Success
+ ? ExitCode.TestSessionAborted
+ : exitCode;
+
///
/// Decides whether the artifacts of a finished run should be consolidated.
///
@@ -1027,9 +1044,9 @@ private static TerminalTestReporter InitializeOutput(int degreeOfParallelism, Pa
ShowFlakyTests = GetShowFlakyTests(parseResult.GetArguments()),
});
- // Ctrl+C handling is wired in Run() through CtrlCCancellationManager so that
- // a second press can force-kill running test app child processes and exit with
- // ExitCode.TestSessionAborted (see issue https://github.com/dotnet/sdk/issues/50732).
+ // Cancellation is wired in Run() through CtrlCCancellationManager so the first Ctrl+C
+ // stops scheduling without interrupting test reporting, while shared lifecycle forceful
+ // cancellation kills running test app child processes.
// Retry-specific rendering is enabled authoritatively by the retry orchestrator handshake.
// Keep the raw option check only for older platform versions that support retries but do not
diff --git a/src/Cli/dotnet/Commands/Test/MTP/TestApplication.cs b/src/Cli/dotnet/Commands/Test/MTP/TestApplication.cs
index f78013f563ac..60ea6bb5b7b1 100644
--- a/src/Cli/dotnet/Commands/Test/MTP/TestApplication.cs
+++ b/src/Cli/dotnet/Commands/Test/MTP/TestApplication.cs
@@ -105,14 +105,15 @@ public async Task RunAsync(CtrlCCancellationManager ctrlC)
{
Logger.LogTrace($"Starting test process with command '{processStartInfo.FileName}' and arguments '{GetArgumentsForLogging(processStartInfo.Arguments)}'.");
- process = Process.Start(processStartInfo)!;
+ process = ctrlC.StartAndRegister(() => Process.Start(processStartInfo));
+ if (process is null)
+ {
+ return ExitCode.TestSessionAborted;
+ }
+
_testRunPolicy?.OnTestApplicationStarted();
testApplicationStarted = true;
- // Register with the Ctrl+C manager so a force-exit (second Ctrl+C) kills this process
- // tree even if the child's own cooperative cancellation hangs.
- ctrlC.Register(process);
-
// Reading from process stdout/stderr is done on separate threads to avoid blocking IO on the threadpool.
// Note: even with 'process.StandardOutput.ReadToEndAsync()' or 'process.BeginOutputReadLine()', we ended up with
// many TP threads just doing synchronous IO, slowing down the progress of the test run.
diff --git a/src/Cli/dotnet/Commands/Test/MTP/TestModulesFilterHandler.cs b/src/Cli/dotnet/Commands/Test/MTP/TestModulesFilterHandler.cs
index 255c931f18aa..fcd72c23c7d6 100644
--- a/src/Cli/dotnet/Commands/Test/MTP/TestModulesFilterHandler.cs
+++ b/src/Cli/dotnet/Commands/Test/MTP/TestModulesFilterHandler.cs
@@ -40,7 +40,7 @@ public TestModulesFilterHandler(string testModules, ParseResult parseResult)
_testModulePaths = GetMatchedModulePaths(_testModules, _testModulesRoot);
}
- public bool Initialize()
+ public bool Initialize(CancellationToken cancellationToken)
{
// If the root directory is not valid, we simply return
if (string.IsNullOrEmpty(_testModulesRoot) || !Directory.Exists(_testModulesRoot))
diff --git a/src/Cli/dotnet/Commands/Test/TestCommandParser.cs b/src/Cli/dotnet/Commands/Test/TestCommandParser.cs
index 0677e6c73c06..72e41a2457c4 100644
--- a/src/Cli/dotnet/Commands/Test/TestCommandParser.cs
+++ b/src/Cli/dotnet/Commands/Test/TestCommandParser.cs
@@ -21,7 +21,7 @@ public static void ConfigureCommand(TestCommandDefinition command)
case TestCommandDefinition.MicrosoftTestingPlatform mtp:
var impl = new MicrosoftTestingPlatformTestCommand();
- mtp.SetAction(parseResult => impl.Run(parseResult, isHelp: false));
+ mtp.SetAction((parseResult, cancellationToken) => impl.Run(parseResult, isHelp: false, cancellationToken));
mtp.CustomHelpLayoutProvider = impl;
break;
diff --git a/src/Cli/dotnet/Commands/Test/VSTest/TestCommand.cs b/src/Cli/dotnet/Commands/Test/VSTest/TestCommand.cs
index 967490f1b135..f3e29c9296e8 100644
--- a/src/Cli/dotnet/Commands/Test/VSTest/TestCommand.cs
+++ b/src/Cli/dotnet/Commands/Test/VSTest/TestCommand.cs
@@ -19,7 +19,7 @@ public class TestCommand(
bool noRestore,
string? msbuildPath = null) : RestoringCommand(msbuildArgs, noRestore, msbuildPath)
{
- public static int Run(ParseResult parseResult)
+ public static int Run(ParseResult parseResult, CancellationToken cancellationToken)
{
parseResult.HandleDebugSwitch();
@@ -50,7 +50,7 @@ public static int Run(ParseResult parseResult)
// When we have settings, we want to exclude the '--' as it doesn't end up in unmatched tokens, so we pass settings.Length - 1
if (ContainsBuiltTestSources(parseResult, GetSettingsCount(settings)))
{
- int exitCode = ForwardToVSTestConsole(parseResult, args, settings, testSessionCorrelationId);
+ int exitCode = ForwardToVSTestConsole(parseResult, args, settings, testSessionCorrelationId, cancellationToken);
// Reached only when the invocation completed, whether the tests passed or failed. An invocation that
// throws or is interrupted deliberately leaves the artifacts on disk for diagnosis.
@@ -58,7 +58,7 @@ public static int Run(ParseResult parseResult)
return exitCode;
}
- int msbuildExitCode = ForwardToMsbuild(parseResult, settings, testSessionCorrelationId);
+ int msbuildExitCode = ForwardToMsbuild(parseResult, settings, testSessionCorrelationId, cancellationToken);
VSTestArtifactsDirectory.Delete();
return msbuildExitCode;
@@ -84,7 +84,7 @@ public static int Run(ParseResult parseResult)
return settings.Length - 1;
}
- private static int ForwardToMsbuild(ParseResult parseResult, string[] settings, string testSessionCorrelationId)
+ private static int ForwardToMsbuild(ParseResult parseResult, string[] settings, string testSessionCorrelationId, CancellationToken cancellationToken)
{
var definition = (TestCommandDefinition.VSTest)parseResult.CommandResult.Command;
@@ -133,10 +133,14 @@ private static int ForwardToMsbuild(ParseResult parseResult, string[] settings,
additionalBuildProperties = ["--property:VsTestUseMSBuildOutput=true"];
}
- int exitCode = FromParseResult(parseResult, settings, testSessionCorrelationId, additionalBuildProperties).Execute();
+ int exitCode = FromParseResult(parseResult, settings, testSessionCorrelationId, additionalBuildProperties).Execute(cancellationToken);
// We run post processing also if execution is failed for possible partial successful result to post process.
- exitCode |= RunArtifactPostProcessingIfNeeded(testSessionCorrelationId, parseResult.GetValue(definition.DiagOption), FeatureFlag.Instance);
+ exitCode |= RunArtifactPostProcessingIfNeeded(
+ testSessionCorrelationId,
+ parseResult.GetValue(definition.DiagOption),
+ FeatureFlag.Instance,
+ cancellationToken);
return exitCode;
}
@@ -156,7 +160,12 @@ static string[] SetLegacyVSTestWorkarounds(string NodeWindowEnvironmentName)
}
}
- private static int ForwardToVSTestConsole(ParseResult parseResult, string[] args, string[] settings, string testSessionCorrelationId)
+ private static int ForwardToVSTestConsole(
+ ParseResult parseResult,
+ string[] args,
+ string[] settings,
+ string testSessionCorrelationId,
+ CancellationToken cancellationToken)
{
var definition = (TestCommandDefinition.VSTest)parseResult.CommandResult.Command;
@@ -177,10 +186,14 @@ private static int ForwardToVSTestConsole(ParseResult parseResult, string[] args
convertedArgs.Add($"--testSessionCorrelationId:{testSessionCorrelationId}");
}
- int exitCode = new VSTestForwardingApp(convertedArgs).Execute();
+ int exitCode = new VSTestForwardingApp(convertedArgs).Execute(cancellationToken);
// We run post processing also if execution is failed for possible partial successful result to post process.
- exitCode |= RunArtifactPostProcessingIfNeeded(testSessionCorrelationId, parseResult.GetValue(definition.DiagOption), FeatureFlag.Instance);
+ exitCode |= RunArtifactPostProcessingIfNeeded(
+ testSessionCorrelationId,
+ parseResult.GetValue(definition.DiagOption),
+ FeatureFlag.Instance,
+ cancellationToken);
return exitCode;
}
@@ -293,7 +306,11 @@ private static TestCommand FromParseResult(ParseResult result, string[] settings
return testCommand;
}
- internal static int RunArtifactPostProcessingIfNeeded(string testSessionCorrelationId, string? diag, FeatureFlag disableFeatureFlag)
+ internal static int RunArtifactPostProcessingIfNeeded(
+ string testSessionCorrelationId,
+ string? diag,
+ FeatureFlag disableFeatureFlag,
+ CancellationToken cancellationToken)
{
if (disableFeatureFlag.IsSet(FeatureFlag.DISABLE_ARTIFACTS_POSTPROCESSING))
{
@@ -320,7 +337,7 @@ internal static int RunArtifactPostProcessingIfNeeded(string testSessionCorrelat
// The post-processing run receives the same artifacts directory as the collecting run did, so it resolves
// the same session subdirectory. The whole directory is removed once the invocation completes, so there is
// nothing to clean up here.
- return new VSTestForwardingApp(artifactsPostProcessArgs).Execute();
+ return new VSTestForwardingApp(artifactsPostProcessArgs).Execute(cancellationToken);
}
///
diff --git a/src/Cli/dotnet/Commands/Tool/Execute/ToolExecuteCommand.cs b/src/Cli/dotnet/Commands/Tool/Execute/ToolExecuteCommand.cs
index d8b045e6131a..36f41d4d635a 100644
--- a/src/Cli/dotnet/Commands/Tool/Execute/ToolExecuteCommand.cs
+++ b/src/Cli/dotnet/Commands/Tool/Execute/ToolExecuteCommand.cs
@@ -53,7 +53,7 @@ public ToolExecuteCommand(ParseResult result, ToolManifestFinder? toolManifestFi
_toolManifestFinder = toolManifestFinder ?? new ToolManifestFinder(new DirectoryPath(currentWorkingDirectory ?? Directory.GetCurrentDirectory()));
}
- public override int Execute() => ExecuteAsync(CancellationToken.None).GetAwaiter().GetResult();
+ public override int Execute(CancellationToken cancellationToken) => ExecuteAsync(cancellationToken).GetAwaiter().GetResult();
internal async Task ExecuteAsync(CancellationToken cancellationToken)
{
@@ -110,7 +110,12 @@ internal async Task ExecuteAsync(CancellationToken cancellationToken)
_toolManifestFinder,
localToolsResolverCache);
- return ToolRunCommand.ExecuteCommand(localToolsCommandResolver, toolManifestPackage.CommandNames.Single().Value, _forwardArguments, _allowRollForward);
+ return ToolRunCommand.ExecuteCommand(
+ localToolsCommandResolver,
+ toolManifestPackage.CommandNames.Single().Value,
+ _forwardArguments,
+ _allowRollForward,
+ cancellationToken);
}
}
@@ -187,6 +192,7 @@ internal async Task ExecuteAsync(CancellationToken cancellationToken)
toolPackage = _toolPackageDownloader.InstallPackage(
downloadPackageLocation,
packageId: packageId,
+ cancellationToken: cancellationToken,
verbosity: _verbosity,
versionRange: new VersionRange(bestVersion!, true, bestVersion!, true),
isGlobalToolRollForward: false,
@@ -199,7 +205,7 @@ internal async Task ExecuteAsync(CancellationToken cancellationToken)
toolExecuteActivity?.SetTag("tool.runner", toolPackage.Command.Runner);
var commandSpec = ToolCommandSpecCreator.CreateToolCommandSpec(toolPackage.Command.Name.Value, toolPackage.Command.Executable.Value, toolPackage.Command.Runner, _allowRollForward, _forwardArguments);
var command = CommandFactoryUsingResolver.Create(commandSpec);
- var result = command.Execute();
+ var result = command.Execute(cancellationToken);
return result.ExitCode;
}
diff --git a/src/Cli/dotnet/Commands/Tool/Install/ProjectRestorer.cs b/src/Cli/dotnet/Commands/Tool/Install/ProjectRestorer.cs
index 80ce0531e945..b32c113c6db4 100644
--- a/src/Cli/dotnet/Commands/Tool/Install/ProjectRestorer.cs
+++ b/src/Cli/dotnet/Commands/Tool/Install/ProjectRestorer.cs
@@ -20,6 +20,7 @@ internal class ProjectRestorer(IReporter reporter = null,
public void Restore(FilePath project,
PackageLocation packageLocation,
+ CancellationToken cancellationToken,
string verbosity = null)
{
List argsToPassToRestore = [project.Value];
@@ -48,7 +49,7 @@ public void Restore(FilePath project,
.OnErrorLine(line => WriteLine(_errorReporter, line, project));
}
- var result = command.Execute();
+ var result = command.Execute(cancellationToken);
if (result.ExitCode != 0)
{
throw new ToolPackageException(CliCommandStrings.ToolInstallationRestoreFailed);
diff --git a/src/Cli/dotnet/Commands/Tool/Install/ToolInstallCommand.cs b/src/Cli/dotnet/Commands/Tool/Install/ToolInstallCommand.cs
index 51f76f3a6fa7..cd49b182c5f5 100644
--- a/src/Cli/dotnet/Commands/Tool/Install/ToolInstallCommand.cs
+++ b/src/Cli/dotnet/Commands/Tool/Install/ToolInstallCommand.cs
@@ -28,8 +28,8 @@ public ToolInstallCommand(
_framework = parseResult.GetValue(Definition.FrameworkOption);
}
- public override int Execute()
- => ExecuteAsync(CancellationToken.None).GetAwaiter().GetResult();
+ public override int Execute(CancellationToken cancellationToken)
+ => ExecuteAsync(cancellationToken).GetAwaiter().GetResult();
internal async Task ExecuteAsync(CancellationToken cancellationToken)
{
@@ -55,7 +55,7 @@ internal async Task ExecuteAsync(CancellationToken cancellationToken)
CliCommandStrings.LocalOptionDoesNotSupportFrameworkOption));
}
- return (_toolInstallLocalCommand ?? new ToolInstallLocalCommand(_parseResult)).Execute();
+ return (_toolInstallLocalCommand ?? new ToolInstallLocalCommand(_parseResult)).Execute(cancellationToken);
}
}
}
diff --git a/src/Cli/dotnet/Commands/Tool/Install/ToolInstallGlobalOrToolPathCommand.cs b/src/Cli/dotnet/Commands/Tool/Install/ToolInstallGlobalOrToolPathCommand.cs
index b5ac8af7b4d8..701d9599505e 100644
--- a/src/Cli/dotnet/Commands/Tool/Install/ToolInstallGlobalOrToolPathCommand.cs
+++ b/src/Cli/dotnet/Commands/Tool/Install/ToolInstallGlobalOrToolPathCommand.cs
@@ -139,7 +139,7 @@ public static T GetValueOrDefault(Option option, T defaultOption, ParseRes
return defaultOption;
}
- public override int Execute() => ExecuteAsync(CancellationToken.None).GetAwaiter().GetResult();
+ public override int Execute(CancellationToken cancellationToken) => ExecuteAsync(cancellationToken).GetAwaiter().GetResult();
internal async Task ExecuteAsync(CancellationToken cancellationToken)
{
@@ -250,6 +250,7 @@ private async Task ExecuteInstallCommandAsync(
IToolPackage newInstalledPackage = toolPackageDownloader.InstallPackage(
new PackageLocation(nugetConfig: GetConfigFile(), sourceFeedOverrides: _source, additionalFeeds: _addSource),
packageId: packageId,
+ cancellationToken: cancellationToken,
versionRange: versionRange,
targetFramework: _framework,
verbosity: _verbosity,
@@ -272,9 +273,16 @@ private async Task ExecuteInstallCommandAsync(
framework = string.IsNullOrEmpty(_framework) ? null : NuGetFramework.Parse(_framework);
}
var shimActivity = Activities.Source.StartActivity("create-shell-shim");
- string appHostSourceDirectory = _shellShimTemplateFinder.ResolveAppHostSourceDirectoryAsync(_architecture, framework, RuntimeInformation.ProcessArchitecture).Result;
-
- shellShimRepository.CreateShim(newInstalledPackage.Command, newInstalledPackage.PackagedShims);
+ string appHostSourceDirectory = _shellShimTemplateFinder.ResolveAppHostSourceDirectoryAsync(
+ _architecture,
+ framework,
+ RuntimeInformation.ProcessArchitecture,
+ cancellationToken).GetAwaiter().GetResult();
+
+ shellShimRepository.CreateShim(
+ newInstalledPackage.Command,
+ cancellationToken,
+ newInstalledPackage.PackagedShims);
shimActivity?.Dispose();
foreach (string w in newInstalledPackage.Warnings)
diff --git a/src/Cli/dotnet/Commands/Tool/Install/ToolInstallLocalCommand.cs b/src/Cli/dotnet/Commands/Tool/Install/ToolInstallLocalCommand.cs
index 03de7b8a4b35..df9dba23446c 100644
--- a/src/Cli/dotnet/Commands/Tool/Install/ToolInstallLocalCommand.cs
+++ b/src/Cli/dotnet/Commands/Tool/Install/ToolInstallLocalCommand.cs
@@ -77,13 +77,13 @@ public ToolInstallLocalCommand(
_allowPackageDowngrade = parseResult.GetValue(Definition.AllowPackageDowngradeOption);
}
- public override int Execute()
+ public override int Execute(CancellationToken cancellationToken)
{
if (_updateAll)
{
foreach (var (manifestPackage, _) in ((IToolManifestInspector)_toolManifestFinder).Inspect())
{
- ExecuteInstallCommand(manifestPackage.PackageId, versionRange: null);
+ ExecuteInstallCommand(manifestPackage.PackageId, versionRange: null, cancellationToken);
}
return 0;
@@ -98,10 +98,10 @@ public override int Execute()
_parseResult.GetValue(Definition.VersionOption),
_parseResult.GetValue(Definition.PrereleaseOption));
- return ExecuteInstallCommand(packageId, versionRange);
+ return ExecuteInstallCommand(packageId, versionRange, cancellationToken);
}
- private int ExecuteInstallCommand(PackageId packageId, VersionRange? versionRange)
+ private int ExecuteInstallCommand(PackageId packageId, VersionRange? versionRange, CancellationToken cancellationToken)
{
FilePath manifestFile = GetManifestFilePath();
@@ -118,11 +118,11 @@ private int ExecuteInstallCommand(PackageId packageId, VersionRange? versionRang
if (!existingPackageWithPackageId.Any())
{
- return InstallNewTool(manifestFile, packageId, versionRange);
+ return InstallNewTool(manifestFile, packageId, versionRange, cancellationToken);
}
var existingPackage = existingPackageWithPackageId.Single();
- var toolDownloadedPackage = _toolLocalPackageInstaller.Install(manifestFile, packageId, versionRange);
+ var toolDownloadedPackage = _toolLocalPackageInstaller.Install(manifestFile, packageId, versionRange, cancellationToken);
InstallToolUpdate(existingPackage, toolDownloadedPackage, manifestFile, packageId);
@@ -179,10 +179,14 @@ public int InstallToolUpdate(ToolManifestPackage existingPackage, IToolPackage t
return 0;
}
- public int InstallNewTool(FilePath manifestFile, PackageId packageId, VersionRange? versionRange)
+ public int InstallNewTool(
+ FilePath manifestFile,
+ PackageId packageId,
+ VersionRange? versionRange,
+ CancellationToken cancellationToken)
{
IToolPackage toolDownloadedPackage =
- _toolLocalPackageInstaller.Install(manifestFile, packageId, versionRange);
+ _toolLocalPackageInstaller.Install(manifestFile, packageId, versionRange, cancellationToken);
_toolManifestEditor.Add(
manifestFile,
diff --git a/src/Cli/dotnet/Commands/Tool/Install/ToolInstallLocalInstaller.cs b/src/Cli/dotnet/Commands/Tool/Install/ToolInstallLocalInstaller.cs
index a29693931cae..8edc995629d8 100644
--- a/src/Cli/dotnet/Commands/Tool/Install/ToolInstallLocalInstaller.cs
+++ b/src/Cli/dotnet/Commands/Tool/Install/ToolInstallLocalInstaller.cs
@@ -23,7 +23,11 @@ internal sealed class ToolInstallLocalInstaller(
private readonly IToolPackageDownloader _toolPackageDownloader = toolPackageDownloader
?? ToolPackageFactory.CreateToolPackageStoresAndDownloader(runtimeJsonPathForTests: runtimeJsonPathForTests).downloader;
- public IToolPackage Install(FilePath manifestFile, PackageId packageId, VersionRange? versionRange)
+ public IToolPackage Install(
+ FilePath manifestFile,
+ PackageId packageId,
+ VersionRange? versionRange,
+ CancellationToken cancellationToken)
{
if (!string.IsNullOrEmpty(configFilePath) && !File.Exists(configFilePath))
{
@@ -54,6 +58,7 @@ public IToolPackage Install(FilePath manifestFile, PackageId packageId, VersionR
additionalFeeds: sources,
rootConfigDirectory: rootConfigDirectory),
packageId,
+ cancellationToken,
verbosity: verbosity,
versionRange,
TargetFrameworkToInstall,
diff --git a/src/Cli/dotnet/Commands/Tool/List/ToolListCommand.cs b/src/Cli/dotnet/Commands/Tool/List/ToolListCommand.cs
index 9f61adac241f..d8b48c6c2f2b 100644
--- a/src/Cli/dotnet/Commands/Tool/List/ToolListCommand.cs
+++ b/src/Cli/dotnet/Commands/Tool/List/ToolListCommand.cs
@@ -14,7 +14,7 @@ internal sealed class ToolListCommand(
private readonly ToolListGlobalOrToolPathCommand _toolListGlobalOrToolPathCommand = toolListGlobalOrToolPathCommand ?? new(result);
private readonly ToolListLocalCommand _toolListLocalCommand = toolListLocalCommand ?? new(result);
- public override int Execute()
+ public override int Execute(CancellationToken cancellationToken)
{
Definition.LocationOptions.EnsureNoConflictGlobalLocalToolPathOption(
_parseResult,
@@ -24,6 +24,6 @@ public override int Execute()
? _toolListGlobalOrToolPathCommand
: _toolListLocalCommand;
- return command.Execute();
+ return command.Execute(cancellationToken);
}
}
diff --git a/src/Cli/dotnet/Commands/Tool/List/ToolListGlobalOrToolPathCommand.cs b/src/Cli/dotnet/Commands/Tool/List/ToolListGlobalOrToolPathCommand.cs
index c77daec25986..2edc21f65bfa 100644
--- a/src/Cli/dotnet/Commands/Tool/List/ToolListGlobalOrToolPathCommand.cs
+++ b/src/Cli/dotnet/Commands/Tool/List/ToolListGlobalOrToolPathCommand.cs
@@ -23,7 +23,7 @@ internal sealed class ToolListGlobalOrToolPathCommand(
private readonly IReporter _errorReporter = reporter ?? Reporter.Error;
private readonly CreateToolPackageStore _createToolPackageStore = createToolPackageStore ?? ToolPackageFactory.CreateToolPackageStoreQuery;
- public override int Execute()
+ public override int Execute(CancellationToken cancellationToken)
{
var toolPathOption = _parseResult.GetValue(Definition.LocationOptions.ToolPathOption);
var packageIdArgument = _parseResult.GetValue(Definition.PackageIdArgument);
diff --git a/src/Cli/dotnet/Commands/Tool/List/ToolListLocalCommand.cs b/src/Cli/dotnet/Commands/Tool/List/ToolListLocalCommand.cs
index bf277d9a472d..33df0aae5a1e 100644
--- a/src/Cli/dotnet/Commands/Tool/List/ToolListLocalCommand.cs
+++ b/src/Cli/dotnet/Commands/Tool/List/ToolListLocalCommand.cs
@@ -29,7 +29,7 @@ public ToolListLocalCommand(
new ToolManifestFinder(new DirectoryPath(Directory.GetCurrentDirectory()));
}
- public override int Execute()
+ public override int Execute(CancellationToken cancellationToken)
{
var packageIdArgument = _parseResult.GetValue(Definition.PackageIdArgument);
PackageId? packageId = string.IsNullOrWhiteSpace(packageIdArgument) ? null : new(packageIdArgument);
diff --git a/src/Cli/dotnet/Commands/Tool/Restore/ToolPackageRestorer.cs b/src/Cli/dotnet/Commands/Tool/Restore/ToolPackageRestorer.cs
index b823a68ec19a..a758d8e96e11 100644
--- a/src/Cli/dotnet/Commands/Tool/Restore/ToolPackageRestorer.cs
+++ b/src/Cli/dotnet/Commands/Tool/Restore/ToolPackageRestorer.cs
@@ -69,6 +69,7 @@ public async Task InstallPackageAsync(
sourceFeedOverrides: _overrideSources,
rootConfigDirectory: package.FirstEffectDirectory),
package.PackageId,
+ cancellationToken,
verbosity: _verbosity,
ToVersionRangeWithOnlyOneVersion(package.Version),
targetFramework,
diff --git a/src/Cli/dotnet/Commands/Tool/Restore/ToolRestoreCommand.cs b/src/Cli/dotnet/Commands/Tool/Restore/ToolRestoreCommand.cs
index 8e992f20cd63..f2d17e186a1d 100644
--- a/src/Cli/dotnet/Commands/Tool/Restore/ToolRestoreCommand.cs
+++ b/src/Cli/dotnet/Commands/Tool/Restore/ToolRestoreCommand.cs
@@ -73,7 +73,7 @@ public ToolRestoreCommand(
_restoreActionConfig = Definition.RestoreOptions.ToRestoreActionConfig(result);
}
- public override int Execute() => ExecuteAsync(CancellationToken.None).GetAwaiter().GetResult();
+ public override int Execute(CancellationToken cancellationToken) => ExecuteAsync(cancellationToken).GetAwaiter().GetResult();
internal async Task ExecuteAsync(CancellationToken cancellationToken)
{
diff --git a/src/Cli/dotnet/Commands/Tool/Run/ToolRunCommand.cs b/src/Cli/dotnet/Commands/Tool/Run/ToolRunCommand.cs
index 72262f1294c0..91e71d9016af 100644
--- a/src/Cli/dotnet/Commands/Tool/Run/ToolRunCommand.cs
+++ b/src/Cli/dotnet/Commands/Tool/Run/ToolRunCommand.cs
@@ -26,12 +26,17 @@ public ToolRunCommand(ParseResult result, LocalToolsCommandResolver? localToolsC
_allowRollForward = result.GetValue(Definition.RollForwardOption);
}
- public override int Execute()
+ public override int Execute(CancellationToken cancellationToken)
{
- return ExecuteCommand(_localToolsCommandResolver, _toolCommandName, _forwardArgument, _allowRollForward);
+ return ExecuteCommand(_localToolsCommandResolver, _toolCommandName, _forwardArgument, _allowRollForward, cancellationToken);
}
- public static int ExecuteCommand(LocalToolsCommandResolver commandResolver, string? toolCommandName, IEnumerable? argumentsToForward, bool allowRollForward)
+ public static int ExecuteCommand(
+ LocalToolsCommandResolver commandResolver,
+ string? toolCommandName,
+ IEnumerable? argumentsToForward,
+ bool allowRollForward,
+ CancellationToken cancellationToken)
{
using var _ = Activities.Source.StartActivity("execute-local-tool");
CommandSpec? commandSpec = commandResolver.ResolveStrict(new CommandResolverArguments()
@@ -46,7 +51,7 @@ public static int ExecuteCommand(LocalToolsCommandResolver commandResolver, stri
throw new GracefulException([string.Format(CliCommandStrings.CannotFindCommandName, toolCommandName)], isUserError: false);
}
- var result = CommandFactoryUsingResolver.Create(commandSpec).Execute();
+ var result = CommandFactoryUsingResolver.Create(commandSpec).Execute(cancellationToken);
return result.ExitCode;
}
}
diff --git a/src/Cli/dotnet/Commands/Tool/Search/ToolSearchCommand.cs b/src/Cli/dotnet/Commands/Tool/Search/ToolSearchCommand.cs
index 3845b81f29d1..d27cbbbe6954 100644
--- a/src/Cli/dotnet/Commands/Tool/Search/ToolSearchCommand.cs
+++ b/src/Cli/dotnet/Commands/Tool/Search/ToolSearchCommand.cs
@@ -17,7 +17,7 @@ internal sealed class ToolSearchCommand(
private readonly INugetToolSearchApiRequest _nugetToolSearchApiRequest = nugetToolSearchApiRequest ?? new NugetToolSearchApiRequest();
private readonly SearchResultPrinter _searchResultPrinter = new(Reporter.Output);
- public override int Execute()
+ public override int Execute(CancellationToken cancellationToken)
{
var isDetailed = _parseResult.GetValue(Definition.DetailOption);
if (!PathUtility.CheckForNuGetInNuGetConfig())
@@ -28,7 +28,7 @@ public override int Execute()
IReadOnlyCollection searchResultPackages =
NugetSearchApiResultDeserializer.Deserialize(
- _nugetToolSearchApiRequest.GetResult(GetNugetSearchApiParameter()).GetAwaiter().GetResult());
+ _nugetToolSearchApiRequest.GetResult(GetNugetSearchApiParameter(), cancellationToken).GetAwaiter().GetResult());
_searchResultPrinter.Print(isDetailed, searchResultPackages);
diff --git a/src/Cli/dotnet/Commands/Tool/Store/StoreCommand.cs b/src/Cli/dotnet/Commands/Tool/Store/StoreCommand.cs
index 1345eb26f2c7..9086adde91b3 100644
--- a/src/Cli/dotnet/Commands/Tool/Store/StoreCommand.cs
+++ b/src/Cli/dotnet/Commands/Tool/Store/StoreCommand.cs
@@ -44,10 +44,10 @@ public static StoreCommand FromParseResult(ParseResult result, string msbuildPat
return new StoreCommand(msbuildArgs, msbuildPath);
}
- public static int Run(ParseResult parseResult)
+ public static int Run(ParseResult parseResult, CancellationToken cancellationToken)
{
parseResult.HandleDebugSwitch();
- return FromParseResult(parseResult).Execute();
+ return FromParseResult(parseResult).Execute(cancellationToken);
}
}
diff --git a/src/Cli/dotnet/Commands/Tool/ToolCommandParser.cs b/src/Cli/dotnet/Commands/Tool/ToolCommandParser.cs
index 2ec4797bd4f6..ae8d8992bb74 100644
--- a/src/Cli/dotnet/Commands/Tool/ToolCommandParser.cs
+++ b/src/Cli/dotnet/Commands/Tool/ToolCommandParser.cs
@@ -2,6 +2,7 @@
// The .NET Foundation licenses this file to you under the MIT license.
using System.CommandLine;
+using Microsoft.DotNet.Cli.CommandLine;
#if !CLI_AOT
using Microsoft.DotNet.Cli.Commands.Tool.Execute;
using Microsoft.DotNet.Cli.Commands.Tool.Install;
@@ -27,26 +28,28 @@ public static void ConfigureCommand(ToolCommandDefinition command)
// `--global`/`--tool-path` variants and `install`/`update`/`restore`/`execute` keep the
// default fallback because they depend on NuGet package install/restore infrastructure that
// isn't AOT-ready. NativeEntryPoint catches the exception and hosts the managed CLI.
- command.ListCommand.SetAction(parseResult =>
+ command.ListCommand.SetAction((parseResult, cancellationToken) =>
command.ListCommand.LocationOptions.IsGlobalOrToolPath(parseResult)
? throw new CommandNotAvailableInAotException()
- : new ToolListLocalCommand(parseResult).Execute());
- command.UninstallCommand.SetAction(parseResult =>
+ : new ToolListLocalCommand(parseResult).Execute(cancellationToken));
+ command.UninstallCommand.SetAction((parseResult, cancellationToken) =>
command.UninstallCommand.LocationOptions.IsGlobalOrToolPath(parseResult)
? throw new CommandNotAvailableInAotException()
- : new ToolUninstallLocalCommand(parseResult).Execute());
- command.RunCommand.SetAction(parseResult => new ToolRunCommand(parseResult).Execute());
- command.SearchCommand.SetAction(parseResult => new ToolSearchCommand(parseResult).Execute());
+ : new ToolUninstallLocalCommand(parseResult).Execute(cancellationToken));
+ command.RunCommand.SetAction((parseResult, cancellationToken) => new ToolRunCommand(parseResult).Execute(cancellationToken));
+ command.SearchCommand.SetAction(
+ (parseResult, cancellationToken) => new ToolSearchCommand(parseResult).Execute(cancellationToken));
#else
command.SetAction(parseResult => parseResult.HandleMissingCommand());
command.InstallCommand.SetAction((parseResult, cancellationToken) =>
new ToolInstallCommand(parseResult).ExecuteAsync(cancellationToken));
- command.UninstallCommand.SetAction(parseResult => new ToolUninstallCommand(parseResult).Execute());
+ command.UninstallCommand.SetAction((parseResult, cancellationToken) => new ToolUninstallCommand(parseResult).Execute(cancellationToken));
command.UpdateCommand.SetAction((parseResult, cancellationToken) =>
new ToolUpdateCommand(parseResult).ExecuteAsync(cancellationToken));
- command.ListCommand.SetAction(parseResult => new ToolListCommand(parseResult).Execute());
- command.RunCommand.SetAction(parseResult => new ToolRunCommand(parseResult).Execute());
- command.SearchCommand.SetAction(parseResult => new ToolSearchCommand(parseResult).Execute());
+ command.ListCommand.SetAction((parseResult, cancellationToken) => new ToolListCommand(parseResult).Execute(cancellationToken));
+ command.RunCommand.SetAction((parseResult, cancellationToken) => new ToolRunCommand(parseResult).Execute(cancellationToken));
+ command.SearchCommand.SetAction(
+ (parseResult, cancellationToken) => new ToolSearchCommand(parseResult).Execute(cancellationToken));
command.RestoreCommand.SetAction((parseResult, cancellationToken) =>
new ToolRestoreCommand(parseResult).ExecuteAsync(cancellationToken));
command.ExecuteCommand.SetAction((parseResult, cancellationToken) =>
diff --git a/src/Cli/dotnet/Commands/Tool/Uninstall/ToolUninstallCommand.cs b/src/Cli/dotnet/Commands/Tool/Uninstall/ToolUninstallCommand.cs
index 9490fa597fd6..b734ee031fb7 100644
--- a/src/Cli/dotnet/Commands/Tool/Uninstall/ToolUninstallCommand.cs
+++ b/src/Cli/dotnet/Commands/Tool/Uninstall/ToolUninstallCommand.cs
@@ -27,7 +27,7 @@ public ToolUninstallCommand(
_toolPath = result.GetValue(Definition.LocationOptions.ToolPathOption);
}
- public override int Execute()
+ public override int Execute(CancellationToken cancellationToken)
{
Definition.LocationOptions.EnsureNoConflictGlobalLocalToolPathOption(
_parseResult,
@@ -39,11 +39,11 @@ public override int Execute()
if (_global || !string.IsNullOrWhiteSpace(_toolPath))
{
- return _toolUninstallGlobalOrToolPathCommand.Execute();
+ return _toolUninstallGlobalOrToolPathCommand.Execute(cancellationToken);
}
else
{
- return _toolUninstallLocalCommand.Execute();
+ return _toolUninstallLocalCommand.Execute(cancellationToken);
}
}
}
diff --git a/src/Cli/dotnet/Commands/Tool/Uninstall/ToolUninstallGlobalOrToolPathCommand.cs b/src/Cli/dotnet/Commands/Tool/Uninstall/ToolUninstallGlobalOrToolPathCommand.cs
index 7007c8042be0..747c26287c30 100644
--- a/src/Cli/dotnet/Commands/Tool/Uninstall/ToolUninstallGlobalOrToolPathCommand.cs
+++ b/src/Cli/dotnet/Commands/Tool/Uninstall/ToolUninstallGlobalOrToolPathCommand.cs
@@ -27,7 +27,7 @@ internal sealed class ToolUninstallGlobalOrToolPathCommand(
private readonly CreateToolPackageStoresAndUninstaller _createToolPackageStoresAndUninstaller = createToolPackageStoreAndUninstaller ??
ToolPackageFactory.CreateToolPackageStoresAndUninstaller;
- public override int Execute()
+ public override int Execute(CancellationToken cancellationToken)
{
var global = _parseResult.GetValue(Definition.LocationOptions.GlobalOption);
var toolPath = _parseResult.GetValue(Definition.LocationOptions.ToolPathOption);
diff --git a/src/Cli/dotnet/Commands/Tool/Uninstall/ToolUninstallLocalCommand.cs b/src/Cli/dotnet/Commands/Tool/Uninstall/ToolUninstallLocalCommand.cs
index b50dac23fc1f..3bb493b93d06 100644
--- a/src/Cli/dotnet/Commands/Tool/Uninstall/ToolUninstallLocalCommand.cs
+++ b/src/Cli/dotnet/Commands/Tool/Uninstall/ToolUninstallLocalCommand.cs
@@ -38,7 +38,7 @@ public ToolUninstallLocalCommand(
_toolManifestEditor = toolManifestEditor ?? new ToolManifestEditor();
}
- public override int Execute()
+ public override int Execute(CancellationToken cancellationToken)
{
(FilePath? manifestFileOptional, string warningMessage) =
_toolManifestFinder.ExplicitManifestOrFindManifestContainPackageId(_explicitManifestFile, _packageId);
diff --git a/src/Cli/dotnet/Commands/Tool/Update/ToolUpdateCommand.cs b/src/Cli/dotnet/Commands/Tool/Update/ToolUpdateCommand.cs
index 17916b6206e3..f4f05e6c5462 100644
--- a/src/Cli/dotnet/Commands/Tool/Update/ToolUpdateCommand.cs
+++ b/src/Cli/dotnet/Commands/Tool/Update/ToolUpdateCommand.cs
@@ -111,8 +111,8 @@ private void EnsureNoConflictUpdateAllVersionOption(
}
}
- public override int Execute()
- => ExecuteAsync(CancellationToken.None).GetAwaiter().GetResult();
+ public override int Execute(CancellationToken cancellationToken)
+ => ExecuteAsync(cancellationToken).GetAwaiter().GetResult();
internal async Task ExecuteAsync(CancellationToken cancellationToken)
{
@@ -140,7 +140,7 @@ internal async Task ExecuteAsync(CancellationToken cancellationToken)
}
else
{
- return _toolUpdateLocalCommand.Execute();
+ return _toolUpdateLocalCommand.Execute(cancellationToken);
}
}
}
diff --git a/src/Cli/dotnet/Commands/Tool/Update/ToolUpdateGlobalOrToolPathCommand.cs b/src/Cli/dotnet/Commands/Tool/Update/ToolUpdateGlobalOrToolPathCommand.cs
index d2b7020dc5eb..fd75731808d9 100644
--- a/src/Cli/dotnet/Commands/Tool/Update/ToolUpdateGlobalOrToolPathCommand.cs
+++ b/src/Cli/dotnet/Commands/Tool/Update/ToolUpdateGlobalOrToolPathCommand.cs
@@ -45,8 +45,8 @@ public ToolUpdateGlobalOrToolPathCommand(ParseResult parseResult,
store: _store);
}
- public override int Execute()
- => ExecuteAsync(CancellationToken.None).GetAwaiter().GetResult();
+ public override int Execute(CancellationToken cancellationToken)
+ => ExecuteAsync(cancellationToken).GetAwaiter().GetResult();
internal async Task ExecuteAsync(CancellationToken cancellationToken)
{
diff --git a/src/Cli/dotnet/Commands/Tool/Update/ToolUpdateLocalCommand.cs b/src/Cli/dotnet/Commands/Tool/Update/ToolUpdateLocalCommand.cs
index 17f696b27330..fda7266ece07 100644
--- a/src/Cli/dotnet/Commands/Tool/Update/ToolUpdateLocalCommand.cs
+++ b/src/Cli/dotnet/Commands/Tool/Update/ToolUpdateLocalCommand.cs
@@ -48,9 +48,9 @@ public ToolUpdateLocalCommand(
_reporter));
}
- public override int Execute()
+ public override int Execute(CancellationToken cancellationToken)
{
- _toolInstallLocalCommand.Value.Execute();
+ _toolInstallLocalCommand.Value.Execute(cancellationToken);
return 0;
}
diff --git a/src/Cli/dotnet/Commands/VSTest/VSTestCommand.cs b/src/Cli/dotnet/Commands/VSTest/VSTestCommand.cs
index 1efea21b8c7a..bac27c3d38fb 100644
--- a/src/Cli/dotnet/Commands/VSTest/VSTestCommand.cs
+++ b/src/Cli/dotnet/Commands/VSTest/VSTestCommand.cs
@@ -12,7 +12,7 @@ namespace Microsoft.DotNet.Cli.Commands.VSTest;
public class VSTestCommand
{
- public static int Run(ParseResult parseResult)
+ public static int Run(ParseResult parseResult, CancellationToken cancellationToken)
{
parseResult.HandleDebugSwitch();
@@ -32,10 +32,14 @@ public static int Run(ParseResult parseResult)
VSTestForwardingApp vsTestforwardingApp = new(args);
- int exitCode = vsTestforwardingApp.Execute();
+ int exitCode = vsTestforwardingApp.Execute(cancellationToken);
// We run post processing also if execution is failed for possible partial successful result to post process.
- exitCode |= TestCommand.RunArtifactPostProcessingIfNeeded(testSessionCorrelationId, diag: null, FeatureFlag.Instance);
+ exitCode |= TestCommand.RunArtifactPostProcessingIfNeeded(
+ testSessionCorrelationId,
+ diag: null,
+ FeatureFlag.Instance,
+ cancellationToken);
// Reached only when the invocation completed, whether the tests passed or failed. An invocation that
// throws or is interrupted deliberately leaves the artifacts on disk for diagnosis.
diff --git a/src/Cli/dotnet/Commands/VSTest/VSTestCommandParser.cs b/src/Cli/dotnet/Commands/VSTest/VSTestCommandParser.cs
index 039c2a52f618..18b62b9c1511 100644
--- a/src/Cli/dotnet/Commands/VSTest/VSTestCommandParser.cs
+++ b/src/Cli/dotnet/Commands/VSTest/VSTestCommandParser.cs
@@ -2,6 +2,7 @@
// The .NET Foundation licenses this file to you under the MIT license.
using System.CommandLine;
+using Microsoft.DotNet.Cli.CommandLine;
namespace Microsoft.DotNet.Cli.Commands.VSTest;
@@ -9,6 +10,6 @@ internal static class VSTestCommandParser
{
public static void ConfigureCommand(VSTestCommandDefinition command)
{
- command.SetAction(VSTestCommand.Run);
+ command.SetAction((parseResult, cancellationToken) => VSTestCommand.Run(parseResult, cancellationToken));
}
}
diff --git a/src/Cli/dotnet/Commands/Workload/Clean/WorkloadCleanCommand.cs b/src/Cli/dotnet/Commands/Workload/Clean/WorkloadCleanCommand.cs
index 773e2cce59e5..c8385f2d42a0 100644
--- a/src/Cli/dotnet/Commands/Workload/Clean/WorkloadCleanCommand.cs
+++ b/src/Cli/dotnet/Commands/Workload/Clean/WorkloadCleanCommand.cs
@@ -46,15 +46,16 @@ public WorkloadCleanCommand(
_workloadInstaller = WorkloadInstallerFactory.GetWorkloadInstaller(Reporter, sdkFeatureBand, creationResult.WorkloadResolver, Verbosity, creationResult.UserProfileDir, VerifySignatures, PackageDownloader, creationResult.DotnetPath);
}
- public override int Execute()
+ public override int Execute(CancellationToken cancellationToken)
{
- ExecuteGarbageCollection();
+ ExecuteGarbageCollection(cancellationToken);
return 0;
}
- private void ExecuteGarbageCollection()
+ private void ExecuteGarbageCollection(CancellationToken cancellationToken)
{
_workloadInstaller.GarbageCollect(workloadVersion => _workloadResolverFactory.CreateForWorkloadSet(_dotnetPath, _sdkVersion.ToString(), _userProfileDir, workloadVersion),
+ cancellationToken,
cleanAllPacks: _cleanAll);
DisplayUninstallableVSWorkloads();
diff --git a/src/Cli/dotnet/Commands/Workload/Config/WorkloadConfigCommand.cs b/src/Cli/dotnet/Commands/Workload/Config/WorkloadConfigCommand.cs
index 67565a46d8fa..5cc4cdbbf9ce 100644
--- a/src/Cli/dotnet/Commands/Workload/Config/WorkloadConfigCommand.cs
+++ b/src/Cli/dotnet/Commands/Workload/Config/WorkloadConfigCommand.cs
@@ -44,7 +44,7 @@ public WorkloadConfigCommand(
_workloadInstaller = WorkloadInstallerFactory.GetWorkloadInstaller(Reporter, _sdkFeatureBand, creationResult.WorkloadResolver, Verbosity, creationResult.UserProfileDir, VerifySignatures, PackageDownloader, creationResult.DotnetPath);
}
- public override int Execute()
+ public override int Execute(CancellationToken cancellationToken)
{
// When we support multiple configuration values, it would be nice if we could process and display them in the order they are passed.
// It seems that the parser doesn't give us a good way to do that, however
diff --git a/src/Cli/dotnet/Commands/Workload/Elevate/WorkloadElevateCommand.cs b/src/Cli/dotnet/Commands/Workload/Elevate/WorkloadElevateCommand.cs
index c300aeec35bb..10760cdc6957 100644
--- a/src/Cli/dotnet/Commands/Workload/Elevate/WorkloadElevateCommand.cs
+++ b/src/Cli/dotnet/Commands/Workload/Elevate/WorkloadElevateCommand.cs
@@ -13,7 +13,7 @@ namespace Microsoft.DotNet.Cli.Commands.Workload.Elevate;
internal class WorkloadElevateCommand(ParseResult parseResult)
: WorkloadCommandBase(parseResult)
{
- public override int Execute()
+ public override int Execute(CancellationToken cancellationToken)
{
if (!OperatingSystem.IsWindows())
{
diff --git a/src/Cli/dotnet/Commands/Workload/History/WorkloadHistoryCommand.cs b/src/Cli/dotnet/Commands/Workload/History/WorkloadHistoryCommand.cs
index dbc522dd4ff1..efd7e1113277 100644
--- a/src/Cli/dotnet/Commands/Workload/History/WorkloadHistoryCommand.cs
+++ b/src/Cli/dotnet/Commands/Workload/History/WorkloadHistoryCommand.cs
@@ -40,7 +40,7 @@ public WorkloadHistoryCommand(
packageSourceLocation: null);
}
- public override int Execute()
+ public override int Execute(CancellationToken cancellationToken)
{
var displayRecords = WorkloadHistoryDisplay.ProcessWorkloadHistoryRecords(_workloadInstaller.GetWorkloadHistoryRecords(_sdkFeatureBand.ToString()), out bool unknownRecordsPresent);
diff --git a/src/Cli/dotnet/Commands/Workload/Install/FileBasedInstaller.cs b/src/Cli/dotnet/Commands/Workload/Install/FileBasedInstaller.cs
index 1d14639910e3..aefc7e42fc53 100644
--- a/src/Cli/dotnet/Commands/Workload/Install/FileBasedInstaller.cs
+++ b/src/Cli/dotnet/Commands/Workload/Install/FileBasedInstaller.cs
@@ -100,8 +100,13 @@ IEnumerable GetPacksInWorkloads(IEnumerable workloadIds)
return packs;
}
- public WorkloadSet InstallWorkloadSet(ITransactionContext context, string workloadSetVersion, DirectoryPath? offlineCache = null)
+ public WorkloadSet InstallWorkloadSet(
+ ITransactionContext context,
+ string workloadSetVersion,
+ CancellationToken cancellationToken,
+ DirectoryPath? offlineCache = null)
{
+ cancellationToken.ThrowIfCancellationRequested();
var workloadSetFeatureBand = SdkFeatureBand.FromWorkloadSetVersion(workloadSetVersion, out var workloadSetPackageVersion);
var workloadSetPackageId = GetManifestPackageId(new ManifestId(WorkloadManifestUpdater.WorkloadSetManifestId), workloadSetFeatureBand);
@@ -109,7 +114,7 @@ public WorkloadSet InstallWorkloadSet(ITransactionContext context, string worklo
try
{
- InstallPackage(workloadSetPackageId, workloadSetPackageVersion, workloadSetPath, context, offlineCache);
+ InstallPackage(workloadSetPackageId, workloadSetPackageVersion, workloadSetPath, context, cancellationToken, offlineCache);
context.Run(
action: () =>
{
@@ -120,7 +125,7 @@ public WorkloadSet InstallWorkloadSet(ITransactionContext context, string worklo
RemoveWorkloadSetInstallationRecord(workloadSetVersion, workloadSetFeatureBand, _sdkFeatureBand);
});
}
- catch (Exception ex)
+ catch (Exception ex) when (ex is not OperationCanceledException)
{
throw new Exception(string.Format(CliCommandStrings.FailedToInstallWorkloadSet, workloadSetVersion, ex.Message), ex);
}
@@ -128,25 +133,40 @@ public WorkloadSet InstallWorkloadSet(ITransactionContext context, string worklo
return WorkloadSet.FromWorkloadSetFolder(workloadSetPath, workloadSetVersion, _sdkFeatureBand);
}
- public WorkloadSet GetWorkloadSetContents(string workloadSetVersion) => GetWorkloadSetContentsAsync(workloadSetVersion).GetAwaiter().GetResult();
+ public WorkloadSet GetWorkloadSetContents(string workloadSetVersion, CancellationToken cancellationToken)
+ => GetWorkloadSetContentsAsync(workloadSetVersion, cancellationToken).GetAwaiter().GetResult();
- public async Task GetWorkloadSetContentsAsync(string workloadSetVersion)
+ public async Task GetWorkloadSetContentsAsync(
+ string workloadSetVersion,
+ CancellationToken cancellationToken)
{
var workloadSetFeatureBand = SdkFeatureBand.FromWorkloadSetVersion(workloadSetVersion, out var workloadSetPackageVersion);
var packagePath = await _nugetPackageDownloader.DownloadPackageAsync(GetManifestPackageId(new ManifestId(WorkloadManifestUpdater.WorkloadSetManifestId), workloadSetFeatureBand),
- new NuGetVersion(workloadSetPackageVersion), _packageSourceLocation);
+ cancellationToken, new NuGetVersion(workloadSetPackageVersion), _packageSourceLocation);
var tempExtractionDir = Path.Combine(_tempPackagesDir.Value, $"{WorkloadManifestUpdater.WorkloadSetManifestId}-{workloadSetPackageVersion}-extracted");
- await ExtractManifestAsync(packagePath, tempExtractionDir);
+ await ExtractManifestAsync(packagePath, tempExtractionDir, cancellationToken);
return WorkloadSet.FromWorkloadSetFolder(tempExtractionDir, workloadSetVersion, _sdkFeatureBand);
}
- public void InstallWorkloads(IEnumerable workloadIds, SdkFeatureBand sdkFeatureBand, ITransactionContext transactionContext, DirectoryPath? offlineCache = null)
+ public void InstallWorkloads(
+ IEnumerable workloadIds,
+ SdkFeatureBand sdkFeatureBand,
+ ITransactionContext transactionContext,
+ CancellationToken cancellationToken,
+ DirectoryPath? offlineCache = null)
{
- InstallWorkloads(workloadIds, sdkFeatureBand, transactionContext, overwriteExistingPacks: false, offlineCache);
+ InstallWorkloads(workloadIds, sdkFeatureBand, transactionContext, cancellationToken, overwriteExistingPacks: false, offlineCache);
}
- public void InstallWorkloads(IEnumerable workloadIds, SdkFeatureBand sdkFeatureBand, ITransactionContext transactionContext, bool overwriteExistingPacks, DirectoryPath? offlineCache = null)
+ public void InstallWorkloads(
+ IEnumerable workloadIds,
+ SdkFeatureBand sdkFeatureBand,
+ ITransactionContext transactionContext,
+ CancellationToken cancellationToken,
+ bool overwriteExistingPacks,
+ DirectoryPath? offlineCache = null)
{
+ cancellationToken.ThrowIfCancellationRequested();
var packInfos = GetPacksInWorkloads(workloadIds);
List packsToInstall = [];
foreach (var packInfo in packInfos)
@@ -169,6 +189,7 @@ public void InstallWorkloads(IEnumerable workloadIds, SdkFeatureBand
{
var packagePath = _nugetPackageDownloader
.DownloadPackageAsync(new PackageId(packInfo.ResolvedPackageId),
+ cancellationToken,
new NuGetVersion(packInfo.Version),
_packageSourceLocation).GetAwaiter().GetResult();
tempFilesToDelete.Add(packagePath);
@@ -215,7 +236,10 @@ public void InstallWorkloads(IEnumerable workloadIds, SdkFeatureBand
}
Directory.CreateDirectory(tempExtractionDir);
- var packFiles = _nugetPackageDownloader.ExtractPackageAsync(packagePath, new DirectoryPath(tempExtractionDir)).GetAwaiter().GetResult();
+ var packFiles = _nugetPackageDownloader.ExtractPackageAsync(
+ packagePath,
+ new DirectoryPath(tempExtractionDir),
+ cancellationToken).GetAwaiter().GetResult();
if (overwriteExistingPacks && Directory.Exists(packInfo.Path))
{
@@ -265,9 +289,19 @@ public void InstallWorkloads(IEnumerable workloadIds, SdkFeatureBand
}
}
- public void RepairWorkloads(IEnumerable workloadIds, SdkFeatureBand sdkFeatureBand, DirectoryPath? offlineCache = null)
+ public void RepairWorkloads(
+ IEnumerable workloadIds,
+ SdkFeatureBand sdkFeatureBand,
+ CancellationToken cancellationToken,
+ DirectoryPath? offlineCache = null)
{
- CliTransaction.RunNew(context => InstallWorkloads(workloadIds, sdkFeatureBand, context, overwriteExistingPacks: true, offlineCache));
+ CliTransaction.RunNew(context => InstallWorkloads(
+ workloadIds,
+ sdkFeatureBand,
+ context,
+ cancellationToken,
+ overwriteExistingPacks: true,
+ offlineCache));
}
string GetManifestInstallDirForFeatureBand(string sdkFeatureBand)
@@ -275,8 +309,13 @@ string GetManifestInstallDirForFeatureBand(string sdkFeatureBand)
return Path.Combine(_workloadRootDir, "sdk-manifests", sdkFeatureBand);
}
- public void InstallWorkloadManifest(ManifestVersionUpdate manifestUpdate, ITransactionContext transactionContext, DirectoryPath? offlineCache = null)
+ public void InstallWorkloadManifest(
+ ManifestVersionUpdate manifestUpdate,
+ ITransactionContext transactionContext,
+ CancellationToken cancellationToken,
+ DirectoryPath? offlineCache = null)
{
+ cancellationToken.ThrowIfCancellationRequested();
var newManifestPath = Path.Combine(GetManifestInstallDirForFeatureBand(manifestUpdate.NewFeatureBand), manifestUpdate.ManifestId.ToString(), manifestUpdate.NewVersion.ToString());
_reporter.WriteLine(string.Format(CliCommandStrings.InstallingWorkloadManifest, manifestUpdate.ManifestId, manifestUpdate.NewVersion));
@@ -285,7 +324,7 @@ public void InstallWorkloadManifest(ManifestVersionUpdate manifestUpdate, ITrans
{
var newManifestPackageId = GetManifestPackageId(manifestUpdate.ManifestId, new SdkFeatureBand(manifestUpdate.NewFeatureBand));
- InstallPackage(newManifestPackageId, manifestUpdate.NewVersion.ToString(), newManifestPath, transactionContext, offlineCache);
+ InstallPackage(newManifestPackageId, manifestUpdate.NewVersion.ToString(), newManifestPath, transactionContext, cancellationToken, offlineCache);
transactionContext.Run(
action: () =>
@@ -297,13 +336,19 @@ public void InstallWorkloadManifest(ManifestVersionUpdate manifestUpdate, ITrans
RemoveManifestInstallationRecord(manifestUpdate.ManifestId, manifestUpdate.NewVersion, new SdkFeatureBand(manifestUpdate.NewFeatureBand), _sdkFeatureBand);
});
}
- catch (Exception e)
+ catch (Exception e) when (e is not OperationCanceledException)
{
throw new Exception(string.Format(CliCommandStrings.FailedToInstallWorkloadManifest, manifestUpdate.ManifestId, manifestUpdate.NewVersion, e.Message), e);
}
}
- void InstallPackage(PackageId packageId, string packageVersion, string targetFolder, ITransactionContext transactionContext, DirectoryPath? offlineCache)
+ void InstallPackage(
+ PackageId packageId,
+ string packageVersion,
+ string targetFolder,
+ ITransactionContext transactionContext,
+ CancellationToken cancellationToken,
+ DirectoryPath? offlineCache)
{
string packagePath = null;
string tempBackupDir = null;
@@ -315,7 +360,7 @@ void InstallPackage(PackageId packageId, string packageVersion, string targetFol
if (offlineCache == null || !offlineCache.HasValue)
{
packagePath = _nugetPackageDownloader.DownloadPackageAsync(packageId,
- new NuGetVersion(packageVersion), _packageSourceLocation).GetAwaiter().GetResult();
+ cancellationToken, new NuGetVersion(packageVersion), _packageSourceLocation).GetAwaiter().GetResult();
}
else
{
@@ -337,7 +382,7 @@ void InstallPackage(PackageId packageId, string packageVersion, string targetFol
FileAccessRetrier.RetryOnMoveAccessFailure(() => DirectoryPath.MoveDirectory(targetFolder, tempBackupDir));
}
- ExtractManifestAsync(packagePath, targetFolder).GetAwaiter().GetResult();
+ ExtractManifestAsync(packagePath, targetFolder, cancellationToken).GetAwaiter().GetResult();
},
rollback: () =>
@@ -394,8 +439,13 @@ public IEnumerable GetDownloads(IEnumerable worklo
return [.. packs.Select(p => new WorkloadDownload(p.Id, p.ResolvedPackageId, p.Version))];
}
- public void GarbageCollect(Func getResolverForWorkloadSet, DirectoryPath? offlineCache = null, bool cleanAllPacks = false)
+ public void GarbageCollect(
+ Func getResolverForWorkloadSet,
+ CancellationToken cancellationToken,
+ DirectoryPath? offlineCache = null,
+ bool cleanAllPacks = false)
{
+ cancellationToken.ThrowIfCancellationRequested();
var globalJsonWorkloadSetVersions = GetGlobalJsonWorkloadSetVersions(_sdkFeatureBand);
var garbageCollector = new WorkloadGarbageCollector(_workloadRootDir,
@@ -654,8 +704,11 @@ public void Shutdown()
public PackageId GetManifestPackageId(ManifestId manifestId, SdkFeatureBand featureBand)
=> _manifestInstaller.GetManifestPackageId(manifestId, featureBand);
- public Task ExtractManifestAsync(string nupkgPath, string targetPath)
- => _manifestInstaller.ExtractManifestAsync(nupkgPath, targetPath);
+ public Task ExtractManifestAsync(
+ string nupkgPath,
+ string targetPath,
+ CancellationToken cancellationToken)
+ => _manifestInstaller.ExtractManifestAsync(nupkgPath, targetPath, cancellationToken);
private bool PackIsInstalled(PackInfo packInfo)
{
diff --git a/src/Cli/dotnet/Commands/Workload/Install/FileBasedManifestInstaller.cs b/src/Cli/dotnet/Commands/Workload/Install/FileBasedManifestInstaller.cs
index 584ded780460..fc1860cd04ad 100644
--- a/src/Cli/dotnet/Commands/Workload/Install/FileBasedManifestInstaller.cs
+++ b/src/Cli/dotnet/Commands/Workload/Install/FileBasedManifestInstaller.cs
@@ -36,8 +36,12 @@ public PackageId GetManifestPackageId(ManifestId manifestId, SdkFeatureBand feat
}
}
- public async Task ExtractManifestAsync(string nupkgPath, string targetPath)
+ public async Task ExtractManifestAsync(
+ string nupkgPath,
+ string targetPath,
+ CancellationToken cancellationToken)
{
+ cancellationToken.ThrowIfCancellationRequested();
var extractionPath = Path.Combine(tempPackagesDir.Value, "dotnet-sdk-advertising-temp", $"{Path.GetFileName(nupkgPath)}-extracted");
if (Directory.Exists(extractionPath))
{
@@ -47,7 +51,10 @@ public async Task ExtractManifestAsync(string nupkgPath, string targetPath)
try
{
Directory.CreateDirectory(extractionPath);
- await nugetPackageDownloader.ExtractPackageAsync(nupkgPath, new DirectoryPath(extractionPath));
+ await nugetPackageDownloader.ExtractPackageAsync(
+ nupkgPath,
+ new DirectoryPath(extractionPath),
+ cancellationToken);
if (Directory.Exists(targetPath))
{
Directory.Delete(targetPath, true);
diff --git a/src/Cli/dotnet/Commands/Workload/Install/IInstaller.cs b/src/Cli/dotnet/Commands/Workload/Install/IInstaller.cs
index 18d2dd3ea256..cb28410f0009 100644
--- a/src/Cli/dotnet/Commands/Workload/Install/IInstaller.cs
+++ b/src/Cli/dotnet/Commands/Workload/Install/IInstaller.cs
@@ -14,17 +14,38 @@ internal interface IInstaller : IWorkloadManifestInstaller
{
int ExitCode { get; }
- WorkloadSet GetWorkloadSetContents(string workloadVersion);
-
- void InstallWorkloads(IEnumerable workloadIds, SdkFeatureBand sdkFeatureBand, ITransactionContext transactionContext, DirectoryPath? offlineCache = null);
-
- void RepairWorkloads(IEnumerable workloadIds, SdkFeatureBand sdkFeatureBand, DirectoryPath? offlineCache = null);
-
- void GarbageCollect(Func getResolverForWorkloadSet, DirectoryPath? offlineCache = null, bool cleanAllPacks = false);
-
- WorkloadSet InstallWorkloadSet(ITransactionContext context, string workloadSetVersion, DirectoryPath? offlineCache = null);
-
- void InstallWorkloadManifest(ManifestVersionUpdate manifestUpdate, ITransactionContext transactionContext, DirectoryPath? offlineCache = null);
+ WorkloadSet GetWorkloadSetContents(string workloadVersion, CancellationToken cancellationToken);
+
+ void InstallWorkloads(
+ IEnumerable workloadIds,
+ SdkFeatureBand sdkFeatureBand,
+ ITransactionContext transactionContext,
+ CancellationToken cancellationToken,
+ DirectoryPath? offlineCache = null);
+
+ void RepairWorkloads(
+ IEnumerable workloadIds,
+ SdkFeatureBand sdkFeatureBand,
+ CancellationToken cancellationToken,
+ DirectoryPath? offlineCache = null);
+
+ void GarbageCollect(
+ Func getResolverForWorkloadSet,
+ CancellationToken cancellationToken,
+ DirectoryPath? offlineCache = null,
+ bool cleanAllPacks = false);
+
+ WorkloadSet InstallWorkloadSet(
+ ITransactionContext context,
+ string workloadSetVersion,
+ CancellationToken cancellationToken,
+ DirectoryPath? offlineCache = null);
+
+ void InstallWorkloadManifest(
+ ManifestVersionUpdate manifestUpdate,
+ ITransactionContext transactionContext,
+ CancellationToken cancellationToken,
+ DirectoryPath? offlineCache = null);
IWorkloadInstallationRecordRepository GetWorkloadInstallationRecordRepository();
diff --git a/src/Cli/dotnet/Commands/Workload/Install/IWorkloadManifestInstaller.cs b/src/Cli/dotnet/Commands/Workload/Install/IWorkloadManifestInstaller.cs
index 058ebc9327da..d555368d8c57 100644
--- a/src/Cli/dotnet/Commands/Workload/Install/IWorkloadManifestInstaller.cs
+++ b/src/Cli/dotnet/Commands/Workload/Install/IWorkloadManifestInstaller.cs
@@ -10,5 +10,5 @@ internal interface IWorkloadManifestInstaller
{
PackageId GetManifestPackageId(ManifestId manifestId, SdkFeatureBand featureBand);
- Task ExtractManifestAsync(string nupkgPath, string targetPath);
+ Task ExtractManifestAsync(string nupkgPath, string targetPath, CancellationToken cancellationToken);
}
diff --git a/src/Cli/dotnet/Commands/Workload/Install/IWorkloadManifestUpdater.cs b/src/Cli/dotnet/Commands/Workload/Install/IWorkloadManifestUpdater.cs
index 0ab59552e0f3..d1a787170bff 100644
--- a/src/Cli/dotnet/Commands/Workload/Install/IWorkloadManifestUpdater.cs
+++ b/src/Cli/dotnet/Commands/Workload/Install/IWorkloadManifestUpdater.cs
@@ -10,9 +10,13 @@ namespace Microsoft.DotNet.Cli.Commands.Workload.Install;
internal interface IWorkloadManifestUpdater
{
- Task UpdateAdvertisingManifestsAsync(bool includePreviews, bool useWorkloadSets = false, DirectoryPath? offlineCache = null);
+ Task UpdateAdvertisingManifestsAsync(
+ CancellationToken cancellationToken,
+ bool includePreviews,
+ bool useWorkloadSets = false,
+ DirectoryPath? offlineCache = null);
- Task BackgroundUpdateAdvertisingManifestsWhenRequiredAsync();
+ Task BackgroundUpdateAdvertisingManifestsWhenRequiredAsync(CancellationToken cancellationToken);
IEnumerable CalculateManifestUpdates();
@@ -21,7 +25,11 @@ internal interface IWorkloadManifestUpdater
IEnumerable CalculateManifestUpdatesFromHistory(WorkloadHistoryState state);
IEnumerable CalculateManifestUpdatesForWorkloadSet(WorkloadSet workloadSet);
- Task> GetManifestPackageDownloadsAsync(bool includePreviews, SdkFeatureBand providedSdkFeatureBand, SdkFeatureBand installedSdkFeatureBand);
+ Task> GetManifestPackageDownloadsAsync(
+ CancellationToken cancellationToken,
+ bool includePreviews,
+ SdkFeatureBand providedSdkFeatureBand,
+ SdkFeatureBand installedSdkFeatureBand);
IEnumerable GetUpdatableWorkloadsToAdvertise(IEnumerable installedWorkloads);
diff --git a/src/Cli/dotnet/Commands/Workload/Install/MsiInstallerBase.cs b/src/Cli/dotnet/Commands/Workload/Install/MsiInstallerBase.cs
index 289e37412a9e..55deab8677ed 100644
--- a/src/Cli/dotnet/Commands/Workload/Install/MsiInstallerBase.cs
+++ b/src/Cli/dotnet/Commands/Workload/Install/MsiInstallerBase.cs
@@ -500,7 +500,7 @@ protected void ReportOnce(string message)
/// The action to perform on the provider key.
/// The provider key to update.
/// The dependent to add or remove.
- protected void UpdateDependent(InstallRequestType requestType, string providerKeyName, string dependent)
+ protected virtual void UpdateDependent(InstallRequestType requestType, string providerKeyName, string dependent)
{
DependencyProvider provider = new(providerKeyName, allUsers: true);
diff --git a/src/Cli/dotnet/Commands/Workload/Install/NetSdkMsiInstallerClient.cs b/src/Cli/dotnet/Commands/Workload/Install/NetSdkMsiInstallerClient.cs
index da5f7cc84e71..8ca77b01a6c4 100644
--- a/src/Cli/dotnet/Commands/Workload/Install/NetSdkMsiInstallerClient.cs
+++ b/src/Cli/dotnet/Commands/Workload/Install/NetSdkMsiInstallerClient.cs
@@ -126,8 +126,13 @@ private class SetupLogReporter(ISetupLogger setupLogger) : IReporter
///
/// Cleans up and removes stale workload packs.
///
- public void GarbageCollect(Func getResolverForWorkloadSet, DirectoryPath? offlineCache = null, bool cleanAllPacks = false)
+ public void GarbageCollect(
+ Func getResolverForWorkloadSet,
+ CancellationToken cancellationToken,
+ DirectoryPath? offlineCache = null,
+ bool cleanAllPacks = false)
{
+ cancellationToken.ThrowIfCancellationRequested();
try
{
ReportPendingReboot();
@@ -189,7 +194,7 @@ public void GarbageCollect(Func getResolverForWorkloa
}
}
- RemoveWorkloadSets(workloadSetsToRemove, offlineCache);
+ RemoveWorkloadSets(workloadSetsToRemove, cancellationToken, offlineCache);
List manifestsToRemove = [];
var installedWorkloadManifests = GetWorkloadManifestRecords();
@@ -239,7 +244,7 @@ public void GarbageCollect(Func getResolverForWorkloa
}
- RemoveWorkloadManifests(manifestsToRemove, offlineCache);
+ RemoveWorkloadManifests(manifestsToRemove, cancellationToken, offlineCache);
// If aliased, the pack records here are the resolved pack from the alias
IEnumerable installedWorkloadPacks = GetWorkloadPackRecords();
@@ -299,7 +304,7 @@ public void GarbageCollect(Func getResolverForWorkloa
}
}
- RemoveWorkloadPacks(packsToRemove, offlineCache);
+ RemoveWorkloadPacks(packsToRemove, cancellationToken, offlineCache);
if (cleanAllPacks)
{
@@ -313,11 +318,19 @@ public void GarbageCollect(Func getResolverForWorkloa
}
}
- public WorkloadSet InstallWorkloadSet(ITransactionContext context, string workloadSetVersion, DirectoryPath? offlineCache)
+ public WorkloadSet InstallWorkloadSet(
+ ITransactionContext context,
+ string workloadSetVersion,
+ CancellationToken cancellationToken,
+ DirectoryPath? offlineCache)
{
+ cancellationToken.ThrowIfCancellationRequested();
ReportPendingReboot();
- var (msi, msiPackageId, installationFolder) = GetWorkloadSetPayload(workloadSetVersion, offlineCache);
+ var (msi, msiPackageId, installationFolder) = GetWorkloadSetPayload(
+ workloadSetVersion,
+ cancellationToken,
+ offlineCache);
context.Run(
action: () =>
@@ -354,7 +367,10 @@ public WorkloadSet InstallWorkloadSet(ITransactionContext context, string worklo
return WorkloadSet.FromWorkloadSetFolder(installationFolder, workloadSetVersion, _sdkFeatureBand);
}
- (MsiPayload msi, string msiPackageId, string installationFolder) GetWorkloadSetPayload(string workloadSetVersion, DirectoryPath? offlineCache)
+ (MsiPayload msi, string msiPackageId, string installationFolder) GetWorkloadSetPayload(
+ string workloadSetVersion,
+ CancellationToken cancellationToken,
+ DirectoryPath? offlineCache)
{
var workloadSetFeatureBand = SdkFeatureBand.FromWorkloadSetVersion(workloadSetVersion, out var msiPackageVersion);
string msiPackageId = GetManifestPackageId(new ManifestId("Microsoft.NET.Workloads"), workloadSetFeatureBand).ToString();
@@ -365,7 +381,7 @@ public WorkloadSet InstallWorkloadSet(ITransactionContext context, string worklo
MsiPayload msi;
try
{
- msi = GetCachedMsiPayload(msiPackageId, msiPackageVersion, offlineCache);
+ msi = GetCachedMsiPayload(msiPackageId, msiPackageVersion, cancellationToken, offlineCache);
}
// Unwrap AggregateException caused by switch from async to sync
catch (Exception ex) when (ex is NuGetPackageNotFoundException || ex.InnerException is NuGetPackageNotFoundException)
@@ -430,15 +446,19 @@ private void UpdateDependentReferenceCounts(
}
}
- private void RemoveWorkloadSets(List workloadSetsToRemove, DirectoryPath? offlineCache)
+ private void RemoveWorkloadSets(
+ List workloadSetsToRemove,
+ CancellationToken cancellationToken,
+ DirectoryPath? offlineCache)
{
foreach (WorkloadSetRecord record in workloadSetsToRemove)
{
+ cancellationToken.ThrowIfCancellationRequested();
DetectState state = DetectPackage(record.ProductCode, out Version _);
if (state == DetectState.Present)
{
string msiNuGetPackageId = $"Microsoft.NET.Workloads.{record.WorkloadSetFeatureBand}.Msi.{HostArchitecture}";
- MsiPayload msi = GetCachedMsiPayload(msiNuGetPackageId, record.WorkloadSetPackageVersion, offlineCache);
+ MsiPayload msi = GetCachedMsiPayload(msiNuGetPackageId, record.WorkloadSetPackageVersion, cancellationToken, offlineCache);
if (!string.Equals(record.ProductCode, msi.ProductCode, StringComparison.OrdinalIgnoreCase))
{
@@ -456,15 +476,19 @@ private void RemoveWorkloadSets(List workloadSetsToRemove, Di
}
}
- private void RemoveWorkloadManifests(List manifestToRemove, DirectoryPath? offlineCache)
+ private void RemoveWorkloadManifests(
+ List manifestToRemove,
+ CancellationToken cancellationToken,
+ DirectoryPath? offlineCache)
{
foreach (WorkloadManifestRecord record in manifestToRemove)
{
+ cancellationToken.ThrowIfCancellationRequested();
DetectState state = DetectPackage(record.ProductCode, out Version _);
if (state == DetectState.Present)
{
string msiNuGetPackageId = $"{record.ManifestId}.Manifest-{record.ManifestFeatureBand}.Msi.{HostArchitecture}";
- MsiPayload msi = GetCachedMsiPayload(msiNuGetPackageId, record.ManifestVersion, offlineCache);
+ MsiPayload msi = GetCachedMsiPayload(msiNuGetPackageId, record.ManifestVersion, cancellationToken, offlineCache);
if (!string.Equals(record.ProductCode, msi.ProductCode, StringComparison.OrdinalIgnoreCase))
{
@@ -482,10 +506,14 @@ private void RemoveWorkloadManifests(List manifestToRemo
}
}
- private void RemoveWorkloadPacks(List packsToRemove, DirectoryPath? offlineCache)
+ private void RemoveWorkloadPacks(
+ List packsToRemove,
+ CancellationToken cancellationToken,
+ DirectoryPath? offlineCache)
{
foreach (WorkloadPackRecord record in packsToRemove)
{
+ cancellationToken.ThrowIfCancellationRequested();
// We need to make sure the product is actually installed and that we're not dealing with an orphaned record, e.g.
// if a previous removal was interrupted. We can't safely clean up orphaned records because it's too expensive
// to query all installed components and determine the product codes associated with the component that
@@ -496,7 +524,7 @@ private void RemoveWorkloadPacks(List packsToRemove, Directo
{
// Manually construct the MSI payload package details
string id = $"{record.MsiId}.Msi.{HostArchitecture}";
- MsiPayload msi = GetCachedMsiPayload(id, record.MsiNuGetVersion.ToString(), offlineCache);
+ MsiPayload msi = GetCachedMsiPayload(id, record.MsiNuGetVersion.ToString(), cancellationToken, offlineCache);
// Make sure the package we have in the cache matches with the record. If it doesn't, we'll do the uninstall
// the hard way
@@ -544,18 +572,35 @@ private void DeleteAllWorkloadInstallationRecords()
public IWorkloadInstallationRecordRepository GetWorkloadInstallationRecordRepository() => RecordRepository;
- public void InstallWorkloadManifest(ManifestVersionUpdate manifestUpdate, ITransactionContext transactionContext, DirectoryPath? offlineCache = null)
+ public void InstallWorkloadManifest(
+ ManifestVersionUpdate manifestUpdate,
+ ITransactionContext transactionContext,
+ CancellationToken cancellationToken,
+ DirectoryPath? offlineCache = null)
{
+ bool shouldRollBackManifest = false;
try
{
transactionContext.Run(
action: () =>
{
- InstallWorkloadManifestImplementation(manifestUpdate, offlineCache);
+ InstallWorkloadManifestImplementation(manifestUpdate, cancellationToken, offlineCache,
+ onInstallAttempt: () => shouldRollBackManifest = true);
},
rollback: () =>
{
- InstallWorkloadManifestImplementation(manifestUpdate, offlineCache: null, action: InstallAction.Uninstall);
+ if (!shouldRollBackManifest)
+ {
+ return;
+ }
+
+ // Rollback has its own lifetime, independent of the cancelled forward operation.
+ using CancellationTokenSource rollbackCancellation = new();
+ InstallWorkloadManifestImplementation(
+ manifestUpdate,
+ rollbackCancellation.Token,
+ offlineCache: null,
+ action: InstallAction.Uninstall);
});
}
catch (Exception e)
@@ -565,8 +610,14 @@ public void InstallWorkloadManifest(ManifestVersionUpdate manifestUpdate, ITrans
}
}
- void InstallWorkloadManifestImplementation(ManifestVersionUpdate manifestUpdate, DirectoryPath? offlineCache = null, InstallAction action = InstallAction.Install)
+ void InstallWorkloadManifestImplementation(
+ ManifestVersionUpdate manifestUpdate,
+ CancellationToken cancellationToken,
+ DirectoryPath? offlineCache = null,
+ InstallAction action = InstallAction.Install,
+ Action onInstallAttempt = null)
{
+ cancellationToken.ThrowIfCancellationRequested();
ReportPendingReboot();
// Rolling back a manifest update after a successful install is essentially a downgrade, which is blocked so we have to
@@ -581,27 +632,38 @@ void InstallWorkloadManifestImplementation(ManifestVersionUpdate manifestUpdate,
Log?.LogMessage($"Resolving {manifestUpdate.ManifestId} ({manifestUpdate.NewVersion}) to {msiPackageId} ({msiPackageVersion}).");
// Retrieve the payload from the MSI package cache.
- MsiPayload msi = GetCachedMsiPayload(msiPackageId, msiPackageVersion, offlineCache);
+ MsiPayload msi = GetCachedMsiPayload(msiPackageId, msiPackageVersion, cancellationToken, offlineCache);
ValidateMsiDatabase(msi);
DetectState state = DetectPackage(msi.ProductCode, out Version installedVersion);
InstallAction plannedAction = PlanPackage(msi, state, action, installedVersion);
+ if (plannedAction == InstallAction.Install)
+ {
+ onInstallAttempt?.Invoke();
+ }
+
ExecutePackage(msi, plannedAction, msiPackageId);
// Update the reference count against the MSI.
UpdateDependent(InstallRequestType.AddDependent, msi.Manifest.ProviderKeyName, _dependent);
}
- public void RepairWorkloads(IEnumerable workloadIds, SdkFeatureBand sdkFeatureBand, DirectoryPath? offlineCache = null)
+ public void RepairWorkloads(
+ IEnumerable workloadIds,
+ SdkFeatureBand sdkFeatureBand,
+ CancellationToken cancellationToken,
+ DirectoryPath? offlineCache = null)
{
+ cancellationToken.ThrowIfCancellationRequested();
try
{
ReportPendingReboot();
foreach (var aquirableMsi in GetMsisForWorkloads(workloadIds))
{
+ cancellationToken.ThrowIfCancellationRequested();
// Retrieve the payload from the MSI package cache.
- MsiPayload msi = GetCachedMsiPayload(aquirableMsi.NuGetPackageId, aquirableMsi.NuGetPackageVersion, offlineCache);
+ MsiPayload msi = GetCachedMsiPayload(aquirableMsi.NuGetPackageId, aquirableMsi.NuGetPackageVersion, cancellationToken, offlineCache);
ValidateMsiDatabase(msi);
DetectState state = DetectPackage(msi, out Version installedVersion);
InstallAction plannedAction = PlanPackage(msi, state, InstallAction.Repair, installedVersion);
@@ -618,14 +680,21 @@ public void RepairWorkloads(IEnumerable workloadIds, SdkFeatureBand
}
}
- public void InstallWorkloads(IEnumerable workloadIds, SdkFeatureBand sdkFeatureBand, ITransactionContext transactionContext, DirectoryPath? offlineCache = null)
+ public void InstallWorkloads(
+ IEnumerable workloadIds,
+ SdkFeatureBand sdkFeatureBand,
+ ITransactionContext transactionContext,
+ CancellationToken cancellationToken,
+ DirectoryPath? offlineCache = null)
{
+ cancellationToken.ThrowIfCancellationRequested();
ReportPendingReboot();
var msisToInstall = GetMsisForWorkloads(workloadIds);
foreach (var msiToInstall in msisToInstall)
{
+ cancellationToken.ThrowIfCancellationRequested();
bool shouldRollBackPack = false;
transactionContext.Run(action: () =>
@@ -633,7 +702,7 @@ public void InstallWorkloads(IEnumerable workloadIds, SdkFeatureBand
try
{
// Retrieve the payload from the MSI package cache.
- MsiPayload msi = GetCachedMsiPayload(msiToInstall.NuGetPackageId, msiToInstall.NuGetPackageVersion, offlineCache);
+ MsiPayload msi = GetCachedMsiPayload(msiToInstall.NuGetPackageId, msiToInstall.NuGetPackageVersion, cancellationToken, offlineCache);
ValidateMsiDatabase(msi);
DetectState state = DetectPackage(msi, out Version installedVersion);
InstallAction plannedAction = PlanPackage(msi, state, InstallAction.Install, installedVersion);
@@ -656,7 +725,9 @@ public void InstallWorkloads(IEnumerable workloadIds, SdkFeatureBand
{
if (shouldRollBackPack)
{
- RollBackMsiInstall(msiToInstall);
+ // Rollback has its own lifetime, independent of the cancelled forward operation.
+ using CancellationTokenSource rollbackCancellation = new();
+ RollBackMsiInstall(msiToInstall, rollbackCancellation.Token);
}
});
}
@@ -671,7 +742,10 @@ public void WriteWorkloadInstallRecords(IEnumerable workloadsToWrite
}
}
- void RollBackMsiInstall(WorkloadDownload msiToRollback, DirectoryPath? offlineCache = null)
+ void RollBackMsiInstall(
+ WorkloadDownload msiToRollback,
+ CancellationToken cancellationToken,
+ DirectoryPath? offlineCache = null)
{
try
{
@@ -679,7 +753,7 @@ void RollBackMsiInstall(WorkloadDownload msiToRollback, DirectoryPath? offlineCa
Log?.LogMessage($"Rolling back workload pack installation for {msiToRollback.NuGetPackageId}.");
// Retrieve the payload from the MSI package cache.
- MsiPayload msi = GetCachedMsiPayload(msiToRollback.NuGetPackageId, msiToRollback.NuGetPackageVersion, offlineCache);
+ MsiPayload msi = GetCachedMsiPayload(msiToRollback.NuGetPackageId, msiToRollback.NuGetPackageVersion, cancellationToken, offlineCache);
ValidateMsiDatabase(msi);
// Check the provider key first in case we were installed and we only need to remove
@@ -741,8 +815,11 @@ public void Shutdown()
public PackageId GetManifestPackageId(ManifestId manifestId, SdkFeatureBand featureBand)
=> _manifestInstaller.GetManifestPackageId(manifestId, featureBand);
- public Task ExtractManifestAsync(string nupkgPath, string targetPath)
- => _manifestInstaller.ExtractManifestAsync(nupkgPath, targetPath);
+ public Task ExtractManifestAsync(
+ string nupkgPath,
+ string targetPath,
+ CancellationToken cancellationToken)
+ => _manifestInstaller.ExtractManifestAsync(nupkgPath, targetPath, cancellationToken);
private void LogPackInfo(PackInfo packInfo)
{
@@ -755,7 +832,7 @@ private void LogPackInfo(PackInfo packInfo)
/// The product code of the MSI to detect.
/// If detected, contains the version of the installed MSI.
/// The detect state of the specified MSI.
- private DetectState DetectPackage(string productCode, out Version installedVersion)
+ protected virtual DetectState DetectPackage(string productCode, out Version installedVersion)
{
installedVersion = default;
uint error = WindowsInstaller.GetProductInfo(productCode, InstallProperty.VERSIONSTRING, out string versionValue);
@@ -854,15 +931,22 @@ private static string GetMsiPackageId(PackInfo packInfo)
/// is downloaded.
/// The directory where the package was extracted.
///
- private string ExtractPackage(string packageId, string packageVersion, DirectoryPath? offlineCache)
+ private string ExtractPackage(
+ string packageId,
+ string packageVersion,
+ CancellationToken cancellationToken,
+ DirectoryPath? offlineCache)
{
string packagePath;
if (offlineCache == null || !offlineCache.HasValue)
{
Reporter.WriteLine($"Downloading {packageId} ({packageVersion})");
- packagePath = _nugetPackageDownloader.DownloadPackageAsync(new PackageId(packageId), new NuGetVersion(packageVersion),
- _packageSourceLocation).Result;
+ packagePath = _nugetPackageDownloader.DownloadPackageAsync(
+ new PackageId(packageId),
+ cancellationToken,
+ new NuGetVersion(packageVersion),
+ _packageSourceLocation).GetAwaiter().GetResult();
Log?.LogMessage($"Downloaded {packageId} ({packageVersion}) to '{packagePath}");
}
else
@@ -881,7 +965,10 @@ private string ExtractPackage(string packageId, string packageVersion, Directory
string extractionDirectory = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString());
Directory.CreateDirectory(extractionDirectory);
Log?.LogMessage($"Extracting '{packageId}' to '{extractionDirectory}'");
- _ = _nugetPackageDownloader.ExtractPackageAsync(packagePath, new DirectoryPath(extractionDirectory)).Result;
+ _ = _nugetPackageDownloader.ExtractPackageAsync(
+ packagePath,
+ new DirectoryPath(extractionDirectory),
+ cancellationToken).GetAwaiter().GetResult();
return extractionDirectory;
}
@@ -917,13 +1004,18 @@ private static IEnumerable GetInstalledFeatureBands(ISetupLogger
/// The path to the offline cache. When , packages are downloaded using the
/// existing package feeds.
/// The MSI payload or if unsuccessful.
- private MsiPayload GetCachedMsiPayload(string packageId, string packageVersion, DirectoryPath? offlineCache)
+ protected virtual MsiPayload GetCachedMsiPayload(
+ string packageId,
+ string packageVersion,
+ CancellationToken cancellationToken,
+ DirectoryPath? offlineCache)
{
+ cancellationToken.ThrowIfCancellationRequested();
if (!Cache.TryGetPayloadFromCache(packageId, packageVersion, out MsiPayload msiPayload))
{
// If it's not fully cached, download or copy if from the local cache and extract the payload package into a
// temporary location and try to cache it again in the MSI cache. We DO NOT trust partially cached packages.
- string extractedPackageRootPath = ExtractPackage(packageId, packageVersion, offlineCache);
+ string extractedPackageRootPath = ExtractPackage(packageId, packageVersion, cancellationToken, offlineCache);
string manifestPath = Path.Combine(extractedPackageRootPath, "data", "msi.json");
Cache.CachePayload(packageId, packageVersion, manifestPath);
Directory.Delete(extractedPackageRootPath, recursive: true);
@@ -944,8 +1036,11 @@ private MsiPayload GetCachedMsiPayload(string packageId, string packageVersion,
/// The action to perform.
/// A friendly name to display to the user when reporting progress. If no value is provided, the MSI
/// filename will be used.
- private void ExecutePackage(MsiPayload msi, InstallAction action, string displayName = null)
+ protected virtual void ExecutePackage(MsiPayload msi, InstallAction action, string displayName = null)
{
+ using IDisposable softCancellationTimeout =
+ ProcessLifecycle.OverrideSoftCancellationTimeout(Timeout.InfiniteTimeSpan);
+
uint error = Error.SUCCESS;
string logFile = GetMsiLogName(msi, action);
string name = string.IsNullOrWhiteSpace(displayName) ? msi.Payload : displayName;
@@ -1024,7 +1119,7 @@ private uint ExecuteWithProgress(string progressLabel, Func installDelegat
/// when retrieving payloads from the cache.
///
/// The payload to validate.
- private void ValidateMsiDatabase(MsiPayload msiPayload)
+ protected virtual void ValidateMsiDatabase(MsiPayload msiPayload)
{
uint error = WindowsInstaller.VerifyPackage(msiPayload.MsiPath);
ExitOnError(error, $"Failed to verify package: {msiPayload.MsiPath}.");
@@ -1128,5 +1223,6 @@ void IInstaller.UpdateInstallMode(SdkFeatureBand sdkFeatureBand, bool? newMode)
// This method should never be called for this kind of installer. It is challenging to get this information from an MSI
// and totally unnecessary as the information is identical from a file-based installer. It was added to IInstaller only
// to facilitate testing. As a consequence, it does not need to be implemented.
- public WorkloadSet GetWorkloadSetContents(string workloadVersion) => throw new NotImplementedException();
+ public WorkloadSet GetWorkloadSetContents(string workloadVersion, CancellationToken cancellationToken)
+ => throw new NotImplementedException();
}
diff --git a/src/Cli/dotnet/Commands/Workload/Install/WindowsMsiManifestInstaller.cs b/src/Cli/dotnet/Commands/Workload/Install/WindowsMsiManifestInstaller.cs
index 02f36d9fe35d..e9a0b2c9808e 100644
--- a/src/Cli/dotnet/Commands/Workload/Install/WindowsMsiManifestInstaller.cs
+++ b/src/Cli/dotnet/Commands/Workload/Install/WindowsMsiManifestInstaller.cs
@@ -82,7 +82,10 @@ public PackageId GetManifestPackageId(ManifestId manifestId, SdkFeatureBand feat
}
}
- public async Task ExtractManifestAsync(string nupkgPath, string targetPath)
+ public async Task ExtractManifestAsync(
+ string nupkgPath,
+ string targetPath,
+ CancellationToken cancellationToken)
{
log?.LogMessage($"ExtractManifestAsync: Extracting '{nupkgPath}' to '{targetPath}'");
string extractionPath = TemporaryDirectory.CreateSubdirectory();
@@ -90,7 +93,10 @@ public async Task ExtractManifestAsync(string nupkgPath, string targetPath)
try
{
log?.LogMessage($"ExtractManifestAsync: Temporary extraction path: '{extractionPath}'");
- await nugetPackageDownloader.ExtractPackageAsync(nupkgPath, new DirectoryPath(extractionPath));
+ await nugetPackageDownloader.ExtractPackageAsync(
+ nupkgPath,
+ new DirectoryPath(extractionPath),
+ cancellationToken);
if (Directory.Exists(targetPath))
{
Directory.Delete(targetPath, true);
diff --git a/src/Cli/dotnet/Commands/Workload/Install/WorkloadAdvertisingManifestUpdater.cs b/src/Cli/dotnet/Commands/Workload/Install/WorkloadAdvertisingManifestUpdater.cs
index 692fcebf05b5..12e0f7e7a908 100644
--- a/src/Cli/dotnet/Commands/Workload/Install/WorkloadAdvertisingManifestUpdater.cs
+++ b/src/Cli/dotnet/Commands/Workload/Install/WorkloadAdvertisingManifestUpdater.cs
@@ -61,28 +61,33 @@ internal class WorkloadAdvertisingManifestUpdater(
private readonly IWorkloadManifestInstaller _workloadManifestInstaller = workloadManifestInstaller;
private readonly bool _displayManifestUpdates = displayManifestUpdates;
- public async Task UpdateAdvertisingManifestsAsync(bool includePreviews, bool useWorkloadSets = false, DirectoryPath? offlineCache = null)
+ public async Task UpdateAdvertisingManifestsAsync(
+ CancellationToken cancellationToken,
+ bool includePreviews,
+ bool useWorkloadSets = false,
+ DirectoryPath? offlineCache = null)
{
if (useWorkloadSets)
{
- await UpdateManifestWithVersionAsync(WorkloadManifestUpdater.WorkloadSetManifestId, includePreviews, _sdkFeatureBand, null, offlineCache);
+ await UpdateManifestWithVersionAsync(cancellationToken, WorkloadManifestUpdater.WorkloadSetManifestId, includePreviews, _sdkFeatureBand, null, offlineCache);
}
else
{
// this updates all the manifests
var manifests = _workloadResolver.GetInstalledManifests();
- await Task.WhenAll(manifests.Select(manifest => UpdateAdvertisingManifestAsync(manifest, includePreviews, offlineCache))).ConfigureAwait(false);
+ await Task.WhenAll(manifests.Select(manifest => UpdateAdvertisingManifestAsync(cancellationToken, manifest, includePreviews, offlineCache))).ConfigureAwait(false);
WriteUpdatableWorkloadsFile();
}
}
- public async Task BackgroundUpdateAdvertisingManifestsWhenRequiredAsync()
+ public async Task BackgroundUpdateAdvertisingManifestsWhenRequiredAsync(CancellationToken cancellationToken)
{
if (!BackgroundUpdatesAreDisabled() &&
AdManifestSentinelIsDueForUpdate() &&
- await UpdatedAdManifestPackagesExistAsync().ConfigureAwait(false))
+ await UpdatedAdManifestPackagesExistAsync(cancellationToken).ConfigureAwait(false))
{
await UpdateAdvertisingManifestsAsync(
+ cancellationToken,
false,
ShouldUseWorkloadSetMode(_sdkFeatureBand, _userProfileDir)).ConfigureAwait(false);
var sentinelPath = GetAdvertisingManifestSentinelPath(_sdkFeatureBand);
@@ -183,6 +188,7 @@ public IEnumerable GetUpdatableWorkloadsToAdvertise(IEnumerable GetInstalledManifestIds() => _workloadResolver.GetInstalledManifests().Select(manifest => new ManifestId(manifest.Id));
private async Task UpdateManifestWithVersionAsync(
+ CancellationToken cancellationToken,
string id,
bool includePreviews,
SdkFeatureBand band,
@@ -204,7 +210,12 @@ private async Task UpdateManifestWithVersionAsync(
Path.GetFileName(path).StartsWith(manifestPackageId.ToString(), StringComparison.OrdinalIgnoreCase) &&
(packageVersion == null || path.Contains(packageVersion.ToString())))
.Max() :
- await _nugetPackageDownloader.DownloadPackageAsync(manifestPackageId, packageVersion: packageVersion, packageSourceLocation: _packageSourceLocation, includePreview: includePreviews);
+ await _nugetPackageDownloader.DownloadPackageAsync(
+ manifestPackageId,
+ cancellationToken,
+ packageVersion: packageVersion,
+ packageSourceLocation: _packageSourceLocation,
+ includePreview: includePreviews);
}
catch (NuGetPackageNotFoundException)
{
@@ -216,7 +227,7 @@ private async Task UpdateManifestWithVersionAsync(
}
var adManifestPath = GetAdvertisingManifestPath(_sdkFeatureBand, manifestId);
- await _workloadManifestInstaller.ExtractManifestAsync(packagePath, adManifestPath);
+ await _workloadManifestInstaller.ExtractManifestAsync(packagePath, adManifestPath, cancellationToken);
// add file that contains the advertised manifest feature band so GetAdvertisingManifestVersionAndWorkloads will use correct feature band, regardless of if rollback occurred or not
File.WriteAllText(Path.Combine(adManifestPath, "AdvertisedManifestFeatureBand.txt"), band.ToString());
@@ -242,7 +253,7 @@ private async Task UpdateManifestWithVersionAsync(
return true;
}
- catch (Exception e)
+ catch (Exception e) when (e is not OperationCanceledException)
{
_reporter.WriteLine(CliCommandStrings.FailedAdManifestUpdate, manifestId, e.Message);
return false;
@@ -270,14 +281,18 @@ private async Task UpdateManifestWithVersionAsync(
}
}
- private async Task UpdateAdvertisingManifestAsync(WorkloadManifestInfo manifest, bool includePreviews, DirectoryPath? offlineCache = null)
+ private async Task UpdateAdvertisingManifestAsync(
+ CancellationToken cancellationToken,
+ WorkloadManifestInfo manifest,
+ bool includePreviews,
+ DirectoryPath? offlineCache = null)
{
var fallbackFeatureBand = new SdkFeatureBand(manifest.ManifestFeatureBand);
// The bands should be checked in the order defined here.
SdkFeatureBand[] bands = [_sdkFeatureBand, fallbackFeatureBand];
foreach (var band in bands.Distinct())
{
- if (await UpdateManifestWithVersionAsync(manifest.Id, includePreviews, band, null, offlineCache))
+ if (await UpdateManifestWithVersionAsync(cancellationToken, manifest.Id, includePreviews, band, null, offlineCache))
{
return;
}
@@ -338,23 +353,25 @@ private bool AdManifestSentinelIsDueForUpdate()
return true;
}
- private async Task UpdatedAdManifestPackagesExistAsync()
+ private async Task UpdatedAdManifestPackagesExistAsync(CancellationToken cancellationToken)
{
var manifests = GetInstalledManifestIds();
// TODO: This doesn't seem to account for differing feature bands
- var availableUpdates = await Task.WhenAll(manifests.Select(manifest => NewerManifestPackageExists(manifest))).ConfigureAwait(false);
+ var availableUpdates = await Task.WhenAll(manifests.Select(manifest => NewerManifestPackageExists(manifest, cancellationToken))).ConfigureAwait(false);
return availableUpdates.Any();
}
- private async Task NewerManifestPackageExists(ManifestId manifest)
+ private async Task NewerManifestPackageExists(ManifestId manifest, CancellationToken cancellationToken)
{
try
{
var currentVersion = NuGetVersion.Parse(_workloadResolver.GetManifestVersion(manifest.ToString()));
- var latestVersion = await _nugetPackageDownloader.GetLatestPackageVersion(_workloadManifestInstaller.GetManifestPackageId(manifest, _sdkFeatureBand));
+ var latestVersion = await _nugetPackageDownloader.GetLatestPackageVersion(
+ _workloadManifestInstaller.GetManifestPackageId(manifest, _sdkFeatureBand),
+ cancellationToken);
return latestVersion > currentVersion;
}
- catch (Exception)
+ catch (Exception ex) when (ex is not OperationCanceledException)
{
return false;
}
diff --git a/src/Cli/dotnet/Commands/Workload/Install/WorkloadInstallCommand.cs b/src/Cli/dotnet/Commands/Workload/Install/WorkloadInstallCommand.cs
index 9a5fd88871aa..0485d16eb8e6 100644
--- a/src/Cli/dotnet/Commands/Workload/Install/WorkloadInstallCommand.cs
+++ b/src/Cli/dotnet/Commands/Workload/Install/WorkloadInstallCommand.cs
@@ -121,7 +121,7 @@ private void ValidateWorkloadIdsInput(IReadOnlyCollection filteredWorklo
}
}
- public override int Execute()
+ public override int Execute(CancellationToken cancellationToken)
{
bool usedRollback = !string.IsNullOrWhiteSpace(_fromRollbackDefinition);
var filteredWorkloadIds = GetValidWorkloadIds();
@@ -141,7 +141,13 @@ public override int Execute()
var existingWorkloads = GetInstalledWorkloads(false);
var workloadsToDownload = existingWorkloads.Union(filteredWorkloadIds.Select(id => new WorkloadId(id))).ToList();
- var packageUrls = GetPackageDownloadUrlsAsync(workloadsToDownload, _skipManifestUpdate, _includePreviews, NullReporter.Instance, packageDownloader).GetAwaiter().GetResult();
+ var packageUrls = GetPackageDownloadUrlsAsync(
+ workloadsToDownload,
+ cancellationToken,
+ _skipManifestUpdate,
+ _includePreviews,
+ NullReporter.Instance,
+ packageDownloader).GetAwaiter().GetResult();
Reporter.WriteLine(JsonSerializer.Serialize(packageUrls, WorkloadInstallJsonSerializerContext.Default.IEnumerableString));
}
@@ -157,9 +163,14 @@ public override int Execute()
var existingWorkloads = GetInstalledWorkloads(false);
var workloadsToDownload = existingWorkloads.Union(filteredWorkloadIds.Select(id => new WorkloadId(id))).ToList();
- DownloadToOfflineCacheAsync(workloadsToDownload, new DirectoryPath(_downloadToCacheOption), _skipManifestUpdate, _includePreviews).Wait();
+ DownloadToOfflineCacheAsync(
+ workloadsToDownload,
+ new DirectoryPath(_downloadToCacheOption),
+ cancellationToken,
+ _skipManifestUpdate,
+ _includePreviews).GetAwaiter().GetResult();
}
- catch (Exception e)
+ catch (Exception e) when (e is not OperationCanceledException)
{
throw new GracefulException(string.Format(CliCommandStrings.WorkloadInstallWorkloadCacheDownloadFailed, e.Message), e, isUserError: false);
}
@@ -194,15 +205,15 @@ public override int Execute()
recorder.Run(() =>
{
- InstallWorkloads(recorder, filteredWorkloadIds);
+ InstallWorkloads(recorder, filteredWorkloadIds, cancellationToken);
});
}
else
{
- InstallWorkloads(null, filteredWorkloadIds);
+ InstallWorkloads(null, filteredWorkloadIds, cancellationToken);
}
}
- catch (Exception e)
+ catch (Exception e) when (e is not OperationCanceledException)
{
if (_shouldShutdownInstaller)
{
@@ -222,7 +233,10 @@ public override int Execute()
return _workloadInstaller.ExitCode;
}
- private void InstallWorkloads(WorkloadHistoryRecorder recorder, IReadOnlyCollection filteredWorkloadIds)
+ private void InstallWorkloads(
+ WorkloadHistoryRecorder recorder,
+ IReadOnlyCollection filteredWorkloadIds,
+ CancellationToken cancellationToken)
{
// Normally we want to validate that the workload IDs specified were valid. However, if there is a global.json file with a workload
// set version specified, and we might install that workload version, then we don't do that check here, because we might not have the right
@@ -259,7 +273,7 @@ private void InstallWorkloads(WorkloadHistoryRecorder recorder, IReadOnlyCollect
{
Reporter.WriteLine(CliCommandStrings.CheckForUpdatedWorkloadManifests);
}
- UpdateWorkloadManifests(recorder, context, offlineCache);
+ UpdateWorkloadManifests(recorder, context, cancellationToken, offlineCache);
}
// Exit early if no valid workloads to install (e.g., only aspire was requested)
@@ -278,7 +292,7 @@ private void InstallWorkloads(WorkloadHistoryRecorder recorder, IReadOnlyCollect
workloadIds = workloadIds.Concat(installedWorkloads).Distinct();
workloadIds = WriteSDKInstallRecordsForVSWorkloads(workloadIds);
- _workloadInstaller.InstallWorkloads(workloadIds, _sdkFeatureBand, context, offlineCache);
+ _workloadInstaller.InstallWorkloads(workloadIds, _sdkFeatureBand, context, cancellationToken, offlineCache);
// Write workload installation records
var recordRepo = _workloadInstaller.GetWorkloadInstallationRecordRepository();
@@ -299,7 +313,13 @@ private void InstallWorkloads(WorkloadHistoryRecorder recorder, IReadOnlyCollect
}
});
- TryRunGarbageCollection(_workloadInstaller, Reporter, Verbosity, workloadSetVersion => _workloadResolverFactory.CreateForWorkloadSet(_dotnetPath, _sdkVersion.ToString(), _userProfileDir, workloadSetVersion), offlineCache);
+ TryRunGarbageCollection(
+ _workloadInstaller,
+ Reporter,
+ Verbosity,
+ workloadSetVersion => _workloadResolverFactory.CreateForWorkloadSet(_dotnetPath, _sdkVersion.ToString(), _userProfileDir, workloadSetVersion),
+ cancellationToken,
+ offlineCache);
Reporter.WriteLine();
Reporter.WriteLine(string.Format(CliCommandStrings.WorkloadInstallInstallationSucceeded, string.Join(" ", newWorkloadInstallRecords)));
@@ -308,13 +328,19 @@ private void InstallWorkloads(WorkloadHistoryRecorder recorder, IReadOnlyCollect
});
}
- internal static void TryRunGarbageCollection(IInstaller workloadInstaller, IReporter reporter, VerbosityOptions verbosity, Func getResolverForWorkloadSet, DirectoryPath? offlineCache = null)
+ internal static void TryRunGarbageCollection(
+ IInstaller workloadInstaller,
+ IReporter reporter,
+ VerbosityOptions verbosity,
+ Func getResolverForWorkloadSet,
+ CancellationToken cancellationToken,
+ DirectoryPath? offlineCache = null)
{
try
{
- workloadInstaller.GarbageCollect(getResolverForWorkloadSet, offlineCache);
+ workloadInstaller.GarbageCollect(getResolverForWorkloadSet, cancellationToken, offlineCache);
}
- catch (Exception e)
+ catch (Exception e) when (e is not OperationCanceledException)
{
// Garbage collection failed, warn user
reporter.WriteLine(string.Format(CliCommandStrings.GarbageCollectionFailed,
@@ -322,25 +348,38 @@ internal static void TryRunGarbageCollection(IInstaller workloadInstaller, IRepo
}
}
- private async Task> GetPackageDownloadUrlsAsync(IEnumerable workloadIds, bool skipManifestUpdate, bool includePreview,
+ private async Task> GetPackageDownloadUrlsAsync(
+ IEnumerable workloadIds,
+ CancellationToken cancellationToken,
+ bool skipManifestUpdate,
+ bool includePreview,
IReporter reporter = null, INuGetPackageDownloader packageDownloader = null)
{
reporter ??= Reporter;
packageDownloader ??= PackageDownloader;
- var downloads = await GetDownloads(workloadIds, skipManifestUpdate, includePreview, reporter: reporter, packageDownloader: packageDownloader);
+ var downloads = await GetDownloads(workloadIds, cancellationToken, skipManifestUpdate, includePreview, reporter: reporter, packageDownloader: packageDownloader);
var urls = new List();
foreach (var download in downloads)
{
- urls.Add(await packageDownloader.GetPackageUrl(new PackageId(download.NuGetPackageId), new NuGetVersion(download.NuGetPackageVersion), _packageSourceLocation));
+ urls.Add(await packageDownloader.GetPackageUrl(
+ new PackageId(download.NuGetPackageId),
+ cancellationToken,
+ new NuGetVersion(download.NuGetPackageVersion),
+ _packageSourceLocation));
}
return urls;
}
- private Task DownloadToOfflineCacheAsync(IEnumerable workloadIds, DirectoryPath offlineCache, bool skipManifestUpdate, bool includePreviews)
+ private Task DownloadToOfflineCacheAsync(
+ IEnumerable workloadIds,
+ DirectoryPath offlineCache,
+ CancellationToken cancellationToken,
+ bool skipManifestUpdate,
+ bool includePreviews)
{
- return GetDownloads(workloadIds, skipManifestUpdate, includePreviews, offlineCache.Value);
+ return GetDownloads(workloadIds, cancellationToken, skipManifestUpdate, includePreviews, offlineCache.Value);
}
private void RunInNewTransaction(Action a)
diff --git a/src/Cli/dotnet/Commands/Workload/Install/WorkloadManifestUpdater.Managed.cs b/src/Cli/dotnet/Commands/Workload/Install/WorkloadManifestUpdater.Managed.cs
index f1fe7bf820e8..63386c4028d4 100644
--- a/src/Cli/dotnet/Commands/Workload/Install/WorkloadManifestUpdater.Managed.cs
+++ b/src/Cli/dotnet/Commands/Workload/Install/WorkloadManifestUpdater.Managed.cs
@@ -54,13 +54,14 @@ public WorkloadManifestUpdater(
}
public Task UpdateAdvertisingManifestsAsync(
+ CancellationToken cancellationToken,
bool includePreviews,
bool useWorkloadSets = false,
DirectoryPath? offlineCache = null)
- => _advertisingUpdater.UpdateAdvertisingManifestsAsync(includePreviews, useWorkloadSets, offlineCache);
+ => _advertisingUpdater.UpdateAdvertisingManifestsAsync(cancellationToken, includePreviews, useWorkloadSets, offlineCache);
- public Task BackgroundUpdateAdvertisingManifestsWhenRequiredAsync()
- => _advertisingUpdater.BackgroundUpdateAdvertisingManifestsWhenRequiredAsync();
+ public Task BackgroundUpdateAdvertisingManifestsWhenRequiredAsync(CancellationToken cancellationToken)
+ => _advertisingUpdater.BackgroundUpdateAdvertisingManifestsWhenRequiredAsync(cancellationToken);
public void DeleteUpdatableWorkloadsFile()
=> _advertisingUpdater.DeleteUpdatableWorkloadsFile();
@@ -112,6 +113,7 @@ private static IEnumerable CalculateManifestRollbacks(
}
public async Task> GetManifestPackageDownloadsAsync(
+ CancellationToken cancellationToken,
bool includePreviews,
SdkFeatureBand providedSdkFeatureBand,
SdkFeatureBand installedSdkFeatureBand)
@@ -135,6 +137,7 @@ public async Task> GetManifestPackageDownloadsAsyn
{
var latestVersion = await _nugetPackageDownloader.GetLatestPackageVersion(
packageId,
+ cancellationToken,
_packageSourceLocation,
includePreviews);
success = true;
@@ -151,7 +154,7 @@ public async Task> GetManifestPackageDownloadsAsyn
_reporter.WriteLine(CliCommandStrings.ManifestPackageUrlNotResolved, providedPackageId);
}
}
- catch
+ catch (Exception ex) when (ex is not OperationCanceledException)
{
_reporter.WriteLine(CliCommandStrings.ManifestPackageUrlNotResolved, manifest.Id);
}
diff --git a/src/Cli/dotnet/Commands/Workload/Install/WorkloadManifestUpdater.cs b/src/Cli/dotnet/Commands/Workload/Install/WorkloadManifestUpdater.cs
index d68eba557268..4d309f082b2e 100644
--- a/src/Cli/dotnet/Commands/Workload/Install/WorkloadManifestUpdater.cs
+++ b/src/Cli/dotnet/Commands/Workload/Install/WorkloadManifestUpdater.cs
@@ -74,14 +74,17 @@ private static WorkloadAdvertisingManifestUpdater GetAdvertisingUpdaterInstance(
return new WorkloadAdvertisingManifestUpdater(reporter, workloadResolver, nugetPackageDownloader, userProfileDir, workloadRecordRepo, manifestInstaller, sdkFeatureBand: sdkFeatureBand);
}
- public static async Task BackgroundUpdateAdvertisingManifestsAsync(string userProfileDir, string workingDirectory = null)
+ public static async Task BackgroundUpdateAdvertisingManifestsAsync(
+ string userProfileDir,
+ string workingDirectory,
+ CancellationToken cancellationToken)
{
try
{
var advertisingUpdater = GetAdvertisingUpdaterInstance(userProfileDir, workingDirectory ?? Directory.GetCurrentDirectory());
- await advertisingUpdater.BackgroundUpdateAdvertisingManifestsWhenRequiredAsync();
+ await advertisingUpdater.BackgroundUpdateAdvertisingManifestsWhenRequiredAsync(cancellationToken);
}
- catch (Exception)
+ catch (Exception ex) when (ex is not OperationCanceledException)
{
// Never surface messages on background updates
}
diff --git a/src/Cli/dotnet/Commands/Workload/InstallingWorkloadCommand.cs b/src/Cli/dotnet/Commands/Workload/InstallingWorkloadCommand.cs
index 6223a6d16ebc..9e83b47505bd 100644
--- a/src/Cli/dotnet/Commands/Workload/InstallingWorkloadCommand.cs
+++ b/src/Cli/dotnet/Commands/Workload/InstallingWorkloadCommand.cs
@@ -190,7 +190,11 @@ InstallStateContents GetCurrentInstallState()
return InstallStateContents.FromPath(path);
}
- protected void UpdateWorkloadManifests(WorkloadHistoryRecorder recorder, ITransactionContext context, DirectoryPath? offlineCache)
+ protected void UpdateWorkloadManifests(
+ WorkloadHistoryRecorder recorder,
+ ITransactionContext context,
+ CancellationToken cancellationToken,
+ DirectoryPath? offlineCache)
{
var shouldUseWorkloadSetsPerInstallState = WorkloadManifestUpdater.ShouldUseWorkloadSetMode(_sdkFeatureBand, _workloadRootDir);
var updateToLatestWorkloadSet = _shouldUseWorkloadSets ?? shouldUseWorkloadSetsPerInstallState && !SpecifiedWorkloadSetVersionInGlobalJson;
@@ -239,7 +243,8 @@ protected void UpdateWorkloadManifests(WorkloadHistoryRecorder recorder, ITransa
PackageDownloader,
_workloadSetVersionFromCommandLine,
_workloadResolver,
- numberOfWorkloadSetsToTake: 1);
+ numberOfWorkloadSetsToTake: 1,
+ cancellationToken);
if (versions is null)
{
@@ -263,7 +268,11 @@ protected void UpdateWorkloadManifests(WorkloadHistoryRecorder recorder, ITransa
if (string.IsNullOrWhiteSpace(resolvedWorkloadSetVersion) && !UseRollback && !FromHistory)
{
- _workloadManifestUpdater.UpdateAdvertisingManifestsAsync(_includePreviews, updateToLatestWorkloadSet, offlineCache).Wait();
+ _workloadManifestUpdater.UpdateAdvertisingManifestsAsync(
+ cancellationToken,
+ _includePreviews,
+ updateToLatestWorkloadSet,
+ offlineCache).GetAwaiter().GetResult();
if (updateToLatestWorkloadSet)
{
resolvedWorkloadSetVersion = _workloadManifestUpdater.GetAdvertisedWorkloadSetVersion();
@@ -289,7 +298,7 @@ protected void UpdateWorkloadManifests(WorkloadHistoryRecorder recorder, ITransa
}
IEnumerable manifestsToUpdate =
- resolvedWorkloadSetVersion != null ? InstallWorkloadSet(context, resolvedWorkloadSetVersion) :
+ resolvedWorkloadSetVersion != null ? InstallWorkloadSet(context, resolvedWorkloadSetVersion, cancellationToken) :
UseRollback ? _workloadManifestUpdater.CalculateManifestRollbacks(_fromRollbackDefinition, recorder) :
FromHistory ? _workloadManifestUpdater.CalculateManifestUpdatesFromHistory(_WorkloadHistoryRecord) :
_workloadManifestUpdater.CalculateManifestUpdates().Select(m => m.ManifestUpdate);
@@ -301,7 +310,7 @@ protected void UpdateWorkloadManifests(WorkloadHistoryRecorder recorder, ITransa
{
foreach (var manifestUpdate in manifestsToUpdate)
{
- _workloadInstaller.InstallWorkloadManifest(manifestUpdate, context, offlineCache);
+ _workloadInstaller.InstallWorkloadManifest(manifestUpdate, context, cancellationToken, offlineCache);
}
if (!SpecifiedWorkloadSetVersionInGlobalJson)
@@ -360,15 +369,23 @@ protected void UpdateWorkloadManifests(WorkloadHistoryRecorder recorder, ITransa
});
}
- private IEnumerable InstallWorkloadSet(ITransactionContext context, string workloadSetVersion)
+ private IEnumerable InstallWorkloadSet(
+ ITransactionContext context,
+ string workloadSetVersion,
+ CancellationToken cancellationToken)
{
Reporter.WriteLine(string.Format(CliCommandStrings.NewWorkloadSet, workloadSetVersion));
- var workloadSet = _workloadInstaller.InstallWorkloadSet(context, workloadSetVersion);
+ var workloadSet = _workloadInstaller.InstallWorkloadSet(context, workloadSetVersion, cancellationToken);
return workloadSet is null ? [] : _workloadManifestUpdater.CalculateManifestUpdatesForWorkloadSet(workloadSet);
}
- protected async Task> GetDownloads(IEnumerable workloadIds, bool skipManifestUpdate, bool includePreview, string downloadFolder = null,
+ protected async Task> GetDownloads(
+ IEnumerable workloadIds,
+ CancellationToken cancellationToken,
+ bool skipManifestUpdate,
+ bool includePreview,
+ string downloadFolder = null,
IReporter reporter = null, INuGetPackageDownloader packageDownloader = null)
{
reporter ??= Reporter;
@@ -393,7 +410,11 @@ protected async Task> GetDownloads(IEnumerable> GetDownloads(IEnumerable> GetDownloads(IEnumerable installedList = _workloadListHelper.InstalledSdkWorkloadIds;
@@ -69,7 +69,7 @@ public override int Execute()
{
_workloadListHelper.CheckTargetSdkVersionIsValid();
- var updateAvailable = GetUpdateAvailable(installedList);
+ var updateAvailable = GetUpdateAvailable(installedList, cancellationToken);
var installed = installedList.Select(id => id.ToString()).ToArray();
ListOutput listOutput = new(installed, [.. updateAvailable]);
@@ -136,10 +136,14 @@ public override int Execute()
return 0;
}
- internal IEnumerable GetUpdateAvailable(IEnumerable installedList)
+ internal IEnumerable GetUpdateAvailable(
+ IEnumerable installedList,
+ CancellationToken cancellationToken)
{
// This was an internal partner ask, and they do not need to support workload sets.
- _workloadManifestUpdater.UpdateAdvertisingManifestsAsync(_includePreviews).Wait();
+ _workloadManifestUpdater.UpdateAdvertisingManifestsAsync(
+ cancellationToken,
+ _includePreviews).GetAwaiter().GetResult();
var manifestsToUpdate = _workloadManifestUpdater.CalculateManifestUpdates();
foreach ((ManifestVersionUpdate manifestUpdate, WorkloadCollection workloads) in manifestsToUpdate)
diff --git a/src/Cli/dotnet/Commands/Workload/Repair/WorkloadRepairCommand.cs b/src/Cli/dotnet/Commands/Workload/Repair/WorkloadRepairCommand.cs
index 4e523eafb594..805a61e1b571 100644
--- a/src/Cli/dotnet/Commands/Workload/Repair/WorkloadRepairCommand.cs
+++ b/src/Cli/dotnet/Commands/Workload/Repair/WorkloadRepairCommand.cs
@@ -62,7 +62,7 @@ public WorkloadRepairCommand(
_recorder.HistoryRecord.CommandName = "repair";
}
- public override int Execute()
+ public override int Execute(CancellationToken cancellationToken)
{
try
{
@@ -81,16 +81,21 @@ public override int Execute()
Reporter.WriteLine(string.Format(CliCommandStrings.RepairingWorkloads, string.Join(" ", workloadIds)));
- ReinstallWorkloadsBasedOnCurrentManifests(workloadIds, sdkFeatureBand);
+ ReinstallWorkloadsBasedOnCurrentManifests(workloadIds, sdkFeatureBand, cancellationToken);
- WorkloadInstallCommand.TryRunGarbageCollection(_workloadInstaller, Reporter, Verbosity, workloadSetVersion => _workloadResolverFactory.CreateForWorkloadSet(_dotnetPath, _sdkVersion.ToString(), _userProfileDir, workloadSetVersion));
+ WorkloadInstallCommand.TryRunGarbageCollection(
+ _workloadInstaller,
+ Reporter,
+ Verbosity,
+ workloadSetVersion => _workloadResolverFactory.CreateForWorkloadSet(_dotnetPath, _sdkVersion.ToString(), _userProfileDir, workloadSetVersion),
+ cancellationToken);
Reporter.WriteLine();
Reporter.WriteLine(string.Format(CliCommandStrings.RepairSucceeded, string.Join(" ", workloadIds)));
Reporter.WriteLine();
});
}
- catch (Exception e)
+ catch (Exception e) when (e is not OperationCanceledException)
{
// Don't show entire stack trace
throw new GracefulException(string.Format(CliCommandStrings.WorkloadRepairFailed, e.Message), e, isUserError: false);
@@ -103,9 +108,12 @@ public override int Execute()
return _workloadInstaller.ExitCode;
}
- private void ReinstallWorkloadsBasedOnCurrentManifests(IEnumerable workloadIds, SdkFeatureBand sdkFeatureBand)
+ private void ReinstallWorkloadsBasedOnCurrentManifests(
+ IEnumerable workloadIds,
+ SdkFeatureBand sdkFeatureBand,
+ CancellationToken cancellationToken)
{
- _workloadInstaller.RepairWorkloads(workloadIds, sdkFeatureBand);
+ _workloadInstaller.RepairWorkloads(workloadIds, sdkFeatureBand, cancellationToken);
}
}
diff --git a/src/Cli/dotnet/Commands/Workload/Restore/WorkloadRestoreCommand.cs b/src/Cli/dotnet/Commands/Workload/Restore/WorkloadRestoreCommand.cs
index 969d6a8e0938..db7f0d46e86e 100644
--- a/src/Cli/dotnet/Commands/Workload/Restore/WorkloadRestoreCommand.cs
+++ b/src/Cli/dotnet/Commands/Workload/Restore/WorkloadRestoreCommand.cs
@@ -26,7 +26,7 @@ public WorkloadRestoreCommand(ParseResult result, IReporter reporter = null)
_slnOrProjectArgument = result.GetValue(Definition.SlnOrProjectArgument);
}
- public override int Execute()
+ public override int Execute(CancellationToken cancellationToken)
{
var workloadResolverFactory = new WorkloadResolverFactory();
var creationResult = workloadResolverFactory.Create();
@@ -46,10 +46,13 @@ public override int Execute()
recorder.Run(() =>
{
// First discover projects. This may return an error if no projects are found, and we shouldn't delay until after Update if that's the case.
- var allProjects = DiscoverAllProjects(Directory.GetCurrentDirectory(), _slnOrProjectArgument).Distinct();
+ var allProjects = DiscoverAllProjects(
+ Directory.GetCurrentDirectory(),
+ cancellationToken,
+ _slnOrProjectArgument).Distinct();
// Then update manifests and install a workload set as necessary
- new WorkloadUpdateCommand(_result, recorder: recorder, isRestoring: true).Execute();
+ new WorkloadUpdateCommand(_result, recorder: recorder, isRestoring: true).Execute(cancellationToken);
List allWorkloadId = RunTargetToGetWorkloadIds(allProjects);
Reporter.WriteLine(string.Format(CliCommandStrings.InstallingWorkloads, string.Join(" ", allWorkloadId)));
@@ -59,7 +62,7 @@ public override int Execute()
skipWorkloadManifestUpdate: true)
{
IsRunningRestore = true
- }.Execute();
+ }.Execute(cancellationToken);
});
workloadInstaller.Shutdown();
@@ -111,7 +114,9 @@ private List RunTargetToGetWorkloadIds(IEnumerable allProjec
}
- internal static List DiscoverAllProjects(string currentDirectory,
+ internal static List DiscoverAllProjects(
+ string currentDirectory,
+ CancellationToken cancellationToken,
IEnumerable slnOrProjectArgument = null)
{
var slnFiles = new List();
@@ -133,7 +138,7 @@ internal static List DiscoverAllProjects(string currentDirectory,
foreach (string solutionFilePath in slnFiles)
{
- var solutionFile = SlnFileFactory.CreateFromFileOrDirectory(solutionFilePath);
+ var solutionFile = SlnFileFactory.CreateFromFileOrDirectory(solutionFilePath, cancellationToken);
projectFiles.AddRange(solutionFile.SolutionProjects.Select(
p => Path.GetFullPath(p.FilePath, Path.GetDirectoryName(solutionFilePath))));
}
diff --git a/src/Cli/dotnet/Commands/Workload/Search/WorkloadSearchCommand.cs b/src/Cli/dotnet/Commands/Workload/Search/WorkloadSearchCommand.cs
index ba681404ffbf..5924f119fe33 100644
--- a/src/Cli/dotnet/Commands/Workload/Search/WorkloadSearchCommand.cs
+++ b/src/Cli/dotnet/Commands/Workload/Search/WorkloadSearchCommand.cs
@@ -34,7 +34,7 @@ public WorkloadSearchCommand(
_workloadResolver = creationResult.WorkloadResolver;
}
- public override int Execute()
+ public override int Execute(CancellationToken cancellationToken)
{
IEnumerable availableWorkloads = _workloadResolver.GetAvailableWorkloads()
.OrderBy(workload => workload.Id);
diff --git a/src/Cli/dotnet/Commands/Workload/Search/WorkloadSearchVersionsCommand.cs b/src/Cli/dotnet/Commands/Workload/Search/WorkloadSearchVersionsCommand.cs
index 2204cafac5a7..05195c30d375 100644
--- a/src/Cli/dotnet/Commands/Workload/Search/WorkloadSearchVersionsCommand.cs
+++ b/src/Cli/dotnet/Commands/Workload/Search/WorkloadSearchVersionsCommand.cs
@@ -81,14 +81,14 @@ private static IInstaller GenerateInstaller(IReporter reporter, SdkFeatureBand s
);
}
- public override int Execute()
+ public override int Execute(CancellationToken cancellationToken)
{
if (_workloadVersion.Count() == 0)
{
List versions;
try
{
- versions = GetVersions(_numberOfWorkloadSetsToTake);
+ versions = GetVersions(_numberOfWorkloadSetsToTake, cancellationToken);
}
catch (NuGetPackageNotFoundException)
{
@@ -110,7 +110,7 @@ public override int Execute()
}
else if (_workloadVersion.Any(v => v.Contains('@')))
{
- var versions = FindBestWorkloadSetsFromComponents()?.Take(_numberOfWorkloadSetsToTake);
+ var versions = FindBestWorkloadSetsFromComponents(cancellationToken)?.Take(_numberOfWorkloadSetsToTake);
if (versions is null)
{
return 0;
@@ -131,7 +131,7 @@ public override int Execute()
}
else
{
- var workloadSet = _installer.GetWorkloadSetContents(_workloadVersion.Single());
+ var workloadSet = _installer.GetWorkloadSetContents(_workloadVersion.Single(), cancellationToken);
if (_workloadSetOutputFormat?.Equals("json", StringComparison.OrdinalIgnoreCase) == true)
{
var set = new WorkloadSet() { ManifestVersions = workloadSet.ManifestVersions };
@@ -153,34 +153,66 @@ public override int Execute()
return 0;
}
- private List GetVersions(int numberOfWorkloadSetsToTake)
+ private List GetVersions(
+ int numberOfWorkloadSetsToTake,
+ CancellationToken cancellationToken)
{
- return GetVersions(numberOfWorkloadSetsToTake, new SdkFeatureBand(_sdkVersion), _installer, _includePreviews, PackageDownloader, _resolver);
+ return GetVersions(
+ numberOfWorkloadSetsToTake,
+ new SdkFeatureBand(_sdkVersion),
+ _installer,
+ _includePreviews,
+ PackageDownloader,
+ _resolver,
+ cancellationToken);
}
- private static List GetVersions(int numberOfWorkloadSetsToTake, SdkFeatureBand featureBand, IInstaller installer, bool includePreviews, INuGetPackageDownloader packageDownloader, IWorkloadResolver resolver)
+ private static List GetVersions(
+ int numberOfWorkloadSetsToTake,
+ SdkFeatureBand featureBand,
+ IInstaller installer,
+ bool includePreviews,
+ INuGetPackageDownloader packageDownloader,
+ IWorkloadResolver resolver,
+ CancellationToken cancellationToken)
{
installer ??= GenerateInstaller(Utils.Reporter.NullReporter, featureBand, resolver, VerbosityOptions.d, interactive: false);
var packageId = installer.GetManifestPackageId(new ManifestId("Microsoft.NET.Workloads"), featureBand);
- return [.. packageDownloader.GetLatestPackageVersions(packageId, numberOfWorkloadSetsToTake, packageSourceLocation: null, includePreview: includePreviews)
+ return [.. packageDownloader.GetLatestPackageVersions(packageId, numberOfWorkloadSetsToTake, cancellationToken, packageSourceLocation: null, includePreview: includePreviews)
.GetAwaiter().GetResult()
.Select(version => featureBand.GetWorkloadSetPackageVersion(version.ToString()))];
}
- private IEnumerable FindBestWorkloadSetsFromComponents()
+ private IEnumerable FindBestWorkloadSetsFromComponents(CancellationToken cancellationToken)
{
- return FindBestWorkloadSetsFromComponents(new SdkFeatureBand(_sdkVersion), _installer, _includePreviews, PackageDownloader, _workloadVersion, _resolver, _numberOfWorkloadSetsToTake);
+ return FindBestWorkloadSetsFromComponents(
+ new SdkFeatureBand(_sdkVersion),
+ _installer,
+ _includePreviews,
+ PackageDownloader,
+ _workloadVersion,
+ _resolver,
+ _numberOfWorkloadSetsToTake,
+ cancellationToken);
}
- public static IEnumerable FindBestWorkloadSetsFromComponents(SdkFeatureBand featureBand, IInstaller installer, bool includePreviews, INuGetPackageDownloader packageDownloader, IEnumerable workloadVersions, IWorkloadResolver resolver, int numberOfWorkloadSetsToTake)
+ public static IEnumerable FindBestWorkloadSetsFromComponents(
+ SdkFeatureBand featureBand,
+ IInstaller installer,
+ bool includePreviews,
+ INuGetPackageDownloader packageDownloader,
+ IEnumerable workloadVersions,
+ IWorkloadResolver resolver,
+ int numberOfWorkloadSetsToTake,
+ CancellationToken cancellationToken)
{
installer ??= GenerateInstaller(Utils.Reporter.NullReporter, featureBand, resolver, VerbosityOptions.d, interactive: false);
List versions;
try
{
// 0 indicates 'give all versions'. Not all will match, so we don't know how many we will need
- versions = GetVersions(0, featureBand, installer, includePreviews, packageDownloader, resolver);
+ versions = GetVersions(0, featureBand, installer, includePreviews, packageDownloader, resolver, cancellationToken);
}
catch (NuGetPackageNotFoundException)
{
@@ -197,7 +229,7 @@ public static IEnumerable FindBestWorkloadSetsFromComponents(SdkFeatureB
// Since these are ordered by version (descending), the first is the highest version
return versions.Where(version =>
{
- var manifestVersions = installer.GetWorkloadSetContents(version).ManifestVersions;
+ var manifestVersions = installer.GetWorkloadSetContents(version, cancellationToken).ManifestVersions;
return manifestIdsAndVersions.All(tuple => manifestVersions.ContainsKey(tuple.Item1) && manifestVersions[tuple.Item1].Version.Equals(tuple.Item2));
}).Take(numberOfWorkloadSetsToTake);
}
diff --git a/src/Cli/dotnet/Commands/Workload/Uninstall/WorkloadUninstallCommand.cs b/src/Cli/dotnet/Commands/Workload/Uninstall/WorkloadUninstallCommand.cs
index d2106a923a6d..1ca6d02d1e70 100644
--- a/src/Cli/dotnet/Commands/Workload/Uninstall/WorkloadUninstallCommand.cs
+++ b/src/Cli/dotnet/Commands/Workload/Uninstall/WorkloadUninstallCommand.cs
@@ -26,7 +26,8 @@ public WorkloadUninstallCommand(
ParseResult parseResult,
IReporter reporter = null,
IWorkloadResolverFactory workloadResolverFactory = null,
- INuGetPackageDownloader nugetPackageDownloader = null)
+ INuGetPackageDownloader nugetPackageDownloader = null,
+ IInstaller workloadInstaller = null)
: base(parseResult, reporter: reporter, nugetPackageDownloader: nugetPackageDownloader)
{
_workloadIds = parseResult.GetValue(Definition.WorkloadIdArgument)
@@ -46,12 +47,12 @@ public WorkloadUninstallCommand(
_userProfileDir = creationResult.UserProfileDir;
var sdkFeatureBand = new SdkFeatureBand(_sdkVersion);
- _workloadInstaller = WorkloadInstallerFactory.GetWorkloadInstaller(Reporter, sdkFeatureBand, creationResult.WorkloadResolver, Verbosity, creationResult.UserProfileDir, VerifySignatures, PackageDownloader, creationResult.DotnetPath);
+ _workloadInstaller = workloadInstaller ?? WorkloadInstallerFactory.GetWorkloadInstaller(Reporter, sdkFeatureBand, creationResult.WorkloadResolver, Verbosity, creationResult.UserProfileDir, VerifySignatures, PackageDownloader, creationResult.DotnetPath);
_recorder = new(_workloadResolverFactory.Create().WorkloadResolver, _workloadInstaller, () => _workloadResolverFactory.CreateForWorkloadSet(_dotnetPath, _sdkVersion.ToString(), _userProfileDir, null));
_recorder.HistoryRecord.CommandName = "uninstall";
}
- public override int Execute()
+ public override int Execute(CancellationToken cancellationToken)
{
try
{
@@ -74,13 +75,20 @@ public override int Execute()
.DeleteWorkloadInstallationRecord(workloadId, featureBand);
}
- _workloadInstaller.GarbageCollect(workloadSetVersion => _workloadResolverFactory.CreateForWorkloadSet(_dotnetPath, _sdkVersion.ToString(), _userProfileDir, workloadSetVersion));
+ _workloadInstaller.GarbageCollect(
+ workloadSetVersion => _workloadResolverFactory.CreateForWorkloadSet(_dotnetPath, _sdkVersion.ToString(), _userProfileDir, workloadSetVersion),
+ cancellationToken);
Reporter.WriteLine();
Reporter.WriteLine(string.Format(CliCommandStrings.WorkloadUninstallUninstallSucceeded, string.Join(" ", _workloadIds)));
Reporter.WriteLine();
});
}
+ catch (OperationCanceledException)
+ {
+ _workloadInstaller.Shutdown();
+ throw;
+ }
catch (Exception e)
{
_workloadInstaller.Shutdown();
diff --git a/src/Cli/dotnet/Commands/Workload/Update/WorkloadUpdateCommand.cs b/src/Cli/dotnet/Commands/Workload/Update/WorkloadUpdateCommand.cs
index 298fb23de979..4d68444a34b4 100644
--- a/src/Cli/dotnet/Commands/Workload/Update/WorkloadUpdateCommand.cs
+++ b/src/Cli/dotnet/Commands/Workload/Update/WorkloadUpdateCommand.cs
@@ -75,15 +75,18 @@ public WorkloadUpdateCommand(
_isRestoring = isRestoring;
}
- public override int Execute()
+ public override int Execute(CancellationToken cancellationToken)
{
if (!string.IsNullOrWhiteSpace(_downloadToCacheOption))
{
try
{
- DownloadToOfflineCacheAsync(new DirectoryPath(_downloadToCacheOption), _includePreviews).Wait();
+ DownloadToOfflineCacheAsync(
+ new DirectoryPath(_downloadToCacheOption),
+ _includePreviews,
+ cancellationToken).GetAwaiter().GetResult();
}
- catch (Exception e)
+ catch (Exception e) when (e is not OperationCanceledException)
{
throw new GracefulException(string.Format(CliCommandStrings.WorkloadUpdateWorkloadCacheDownloadFailed, e.Message), e, isUserError: false);
}
@@ -95,19 +98,24 @@ public override int Execute()
VerifySignatures,
restoreActionConfig: RestoreActionConfiguration);
- var packageUrls = GetUpdatablePackageUrlsAsync(_includePreviews, NullReporter.Instance, packageDownloader).GetAwaiter().GetResult();
+ var packageUrls = GetUpdatablePackageUrlsAsync(
+ _includePreviews,
+ cancellationToken,
+ NullReporter.Instance,
+ packageDownloader).GetAwaiter().GetResult();
Reporter.WriteLine(JsonSerializer.Serialize(packageUrls, WorkloadInstallJsonSerializerContext.Default.IEnumerableString));
}
else if (_adManifestOnlyOption)
{
bool? shouldUseWorkloadSetsPerGlobalJson = _shouldUseWorkloadSets ?? (SpecifiedWorkloadSetVersionInGlobalJson ? true : null);
_workloadManifestUpdater.UpdateAdvertisingManifestsAsync(
+ cancellationToken,
_includePreviews,
shouldUseWorkloadSetsPerGlobalJson ?? WorkloadManifestUpdater.ShouldUseWorkloadSetMode(_sdkFeatureBand, _workloadRootDir),
string.IsNullOrWhiteSpace(_fromCacheOption) ?
null :
new DirectoryPath(_fromCacheOption))
- .Wait();
+ .GetAwaiter().GetResult();
Reporter.WriteLine();
Reporter.WriteLine(CliCommandStrings.WorkloadUpdateAdManifestsSucceeded);
}
@@ -125,15 +133,15 @@ public override int Execute()
{
_recorder.Run(() =>
{
- UpdateWorkloads();
+ UpdateWorkloads(cancellationToken);
});
}
else
{
- UpdateWorkloads();
+ UpdateWorkloads(cancellationToken);
}
}
- catch (Exception e)
+ catch (Exception e) when (e is not OperationCanceledException)
{
// Don't show entire stack trace
throw new GracefulException(string.Format(CliCommandStrings.WorkloadUpdateFailed, e.Message), e, isUserError: false);
@@ -147,13 +155,13 @@ public override int Execute()
return _workloadInstaller.ExitCode;
}
- private void UpdateWorkloads()
+ private void UpdateWorkloads(CancellationToken cancellationToken)
{
DirectoryPath? offlineCache = string.IsNullOrWhiteSpace(_fromCacheOption) ? null : new DirectoryPath(_fromCacheOption);
var workloadIds = Enumerable.Empty();
RunInNewTransaction(context =>
{
- UpdateWorkloadManifests(_recorder, context, offlineCache);
+ UpdateWorkloadManifests(_recorder, context, cancellationToken, offlineCache);
// This depends on getting the available workloads, so it needs to run after manifests have potentially been installed
workloadIds = WriteSDKInstallRecordsForVSWorkloads(GetUpdatableWorkloads());
@@ -162,16 +170,22 @@ private void UpdateWorkloads()
{
if (!_historyManifestOnlyOption)
{
- UpdateInstalledWorkloadsFromHistory(context, offlineCache);
+ UpdateInstalledWorkloadsFromHistory(context, cancellationToken, offlineCache);
}
}
else
{
- _workloadInstaller.InstallWorkloads(workloadIds, _sdkFeatureBand, context, offlineCache);
+ _workloadInstaller.InstallWorkloads(workloadIds, _sdkFeatureBand, context, cancellationToken, offlineCache);
}
});
- WorkloadInstallCommand.TryRunGarbageCollection(_workloadInstaller, Reporter, Verbosity, workloadSetVersion => _workloadResolverFactory.CreateForWorkloadSet(_dotnetPath, _sdkVersion.ToString(), _userProfileDir, workloadSetVersion), offlineCache);
+ WorkloadInstallCommand.TryRunGarbageCollection(
+ _workloadInstaller,
+ Reporter,
+ Verbosity,
+ workloadSetVersion => _workloadResolverFactory.CreateForWorkloadSet(_dotnetPath, _sdkVersion.ToString(), _userProfileDir, workloadSetVersion),
+ cancellationToken,
+ offlineCache);
// TODO: potentially only do this in some cases (ie not if global.json specifies workload set)
_workloadManifestUpdater.DeleteUpdatableWorkloadsFile();
@@ -181,7 +195,10 @@ private void UpdateWorkloads()
Reporter.WriteLine();
}
- private void UpdateInstalledWorkloadsFromHistory(ITransactionContext context, DirectoryPath? offlineCache)
+ private void UpdateInstalledWorkloadsFromHistory(
+ ITransactionContext context,
+ CancellationToken cancellationToken,
+ DirectoryPath? offlineCache)
{
if (FromHistory)
{
@@ -192,7 +209,7 @@ private void UpdateInstalledWorkloadsFromHistory(ITransactionContext context, Di
var workloadsToInstall = desiredWorkloads.Except(installedWorkloads).ToList();
var workloadsToUninstall = installedWorkloads.Except(desiredWorkloads).ToList();
- _workloadInstaller.InstallWorkloads(workloadsToInstall, _sdkFeatureBand, context, offlineCache);
+ _workloadInstaller.InstallWorkloads(workloadsToInstall, _sdkFeatureBand, context, cancellationToken, offlineCache);
foreach (var id in workloadsToUninstall)
{
@@ -202,21 +219,32 @@ private void UpdateInstalledWorkloadsFromHistory(ITransactionContext context, Di
}
}
- private async Task DownloadToOfflineCacheAsync(DirectoryPath offlineCache, bool includePreviews)
+ private async Task DownloadToOfflineCacheAsync(
+ DirectoryPath offlineCache,
+ bool includePreviews,
+ CancellationToken cancellationToken)
{
- await GetDownloads(GetUpdatableWorkloads(), skipManifestUpdate: false, includePreviews, offlineCache.Value);
+ await GetDownloads(GetUpdatableWorkloads(), cancellationToken, skipManifestUpdate: false, includePreviews, offlineCache.Value);
}
- private async Task> GetUpdatablePackageUrlsAsync(bool includePreview, IReporter reporter = null, INuGetPackageDownloader packageDownloader = null)
+ private async Task> GetUpdatablePackageUrlsAsync(
+ bool includePreview,
+ CancellationToken cancellationToken,
+ IReporter reporter = null,
+ INuGetPackageDownloader packageDownloader = null)
{
reporter ??= Reporter;
packageDownloader ??= PackageDownloader;
- var downloads = await GetDownloads(GetUpdatableWorkloads(reporter), skipManifestUpdate: false, includePreview, reporter: reporter, packageDownloader: packageDownloader);
+ var downloads = await GetDownloads(GetUpdatableWorkloads(reporter), cancellationToken, skipManifestUpdate: false, includePreview, reporter: reporter, packageDownloader: packageDownloader);
var urls = new List();
foreach (var download in downloads)
{
- urls.Add(await packageDownloader.GetPackageUrl(new PackageId(download.NuGetPackageId), new NuGetVersion(download.NuGetPackageVersion), _packageSourceLocation));
+ urls.Add(await packageDownloader.GetPackageUrl(
+ new PackageId(download.NuGetPackageId),
+ cancellationToken,
+ new NuGetVersion(download.NuGetPackageVersion),
+ _packageSourceLocation));
}
return urls;
diff --git a/src/Cli/dotnet/Commands/Workload/WorkloadCommandParser.cs b/src/Cli/dotnet/Commands/Workload/WorkloadCommandParser.cs
index 91bc0921d6f8..fa4bc8b9bdd5 100644
--- a/src/Cli/dotnet/Commands/Workload/WorkloadCommandParser.cs
+++ b/src/Cli/dotnet/Commands/Workload/WorkloadCommandParser.cs
@@ -3,6 +3,7 @@
using System.CommandLine;
using System.CommandLine.Invocation;
+using Microsoft.DotNet.Cli.CommandLine;
using Microsoft.DotNet.Cli.Commands.Workload.Clean;
using Microsoft.DotNet.Cli.Commands.Workload.Config;
using Microsoft.DotNet.Cli.Commands.Workload.Elevate;
@@ -29,18 +30,18 @@ public static void ConfigureCommand(WorkloadCommandDefinition def)
def.InfoOption.Action = new ShowWorkloadsInfoAction();
def.VersionOption.Action = new ShowWorkloadsVersionOption();
- def.InstallCommand.SetAction(parseResult => new WorkloadInstallCommand(parseResult).Execute());
- def.UpdateCommand.SetAction(parseResult => new WorkloadUpdateCommand(parseResult).Execute());
- def.ListCommand.SetAction(parseResult => new WorkloadListCommand(parseResult).Execute());
- def.SearchCommand.SetAction(parseResult => new WorkloadSearchCommand(parseResult).Execute());
- def.SearchCommand.VersionCommand.SetAction(parseResult => new WorkloadSearchVersionsCommand(parseResult).Execute());
- def.UninstallCommand.SetAction(parseResult => new WorkloadUninstallCommand(parseResult).Execute());
- def.RepairCommand.SetAction(parseResult => new WorkloadRepairCommand(parseResult).Execute());
- def.RestoreCommand.SetAction(parseResult => new WorkloadRestoreCommand(parseResult).Execute());
- def.CleanCommand.SetAction(parseResult => new WorkloadCleanCommand(parseResult).Execute());
- def.ElevateCommand.SetAction(parseResult => new WorkloadElevateCommand(parseResult).Execute());
- def.ConfigCommand.SetAction(parseResult => new WorkloadConfigCommand(parseResult).Execute());
- def.HistoryCommand.SetAction(parseResult => new WorkloadHistoryCommand(parseResult).Execute());
+ def.InstallCommand.SetAction((parseResult, cancellationToken) => new WorkloadInstallCommand(parseResult).Execute(cancellationToken));
+ def.UpdateCommand.SetAction((parseResult, cancellationToken) => new WorkloadUpdateCommand(parseResult).Execute(cancellationToken));
+ def.ListCommand.SetAction((parseResult, cancellationToken) => new WorkloadListCommand(parseResult).Execute(cancellationToken));
+ def.SearchCommand.SetAction((parseResult, cancellationToken) => new WorkloadSearchCommand(parseResult).Execute(cancellationToken));
+ def.SearchCommand.VersionCommand.SetAction((parseResult, cancellationToken) => new WorkloadSearchVersionsCommand(parseResult).Execute(cancellationToken));
+ def.UninstallCommand.SetAction((parseResult, cancellationToken) => new WorkloadUninstallCommand(parseResult).Execute(cancellationToken));
+ def.RepairCommand.SetAction((parseResult, cancellationToken) => new WorkloadRepairCommand(parseResult).Execute(cancellationToken));
+ def.RestoreCommand.SetAction((parseResult, cancellationToken) => new WorkloadRestoreCommand(parseResult).Execute(cancellationToken));
+ def.CleanCommand.SetAction((parseResult, cancellationToken) => new WorkloadCleanCommand(parseResult).Execute(cancellationToken));
+ def.ElevateCommand.SetAction((parseResult, cancellationToken) => new WorkloadElevateCommand(parseResult).Execute(cancellationToken));
+ def.ConfigCommand.SetAction((parseResult, cancellationToken) => new WorkloadConfigCommand(parseResult).Execute(cancellationToken));
+ def.HistoryCommand.SetAction((parseResult, cancellationToken) => new WorkloadHistoryCommand(parseResult).Execute(cancellationToken));
}
public static RestoreActionConfig ToRestoreActionConfig(this NuGetRestoreOptions options, ParseResult parseResult)
diff --git a/src/Cli/dotnet/Commands/Workload/WorkloadIntegrityChecker.cs b/src/Cli/dotnet/Commands/Workload/WorkloadIntegrityChecker.cs
index 7002d4c02aaa..dd82f5fd9a5e 100644
--- a/src/Cli/dotnet/Commands/Workload/WorkloadIntegrityChecker.cs
+++ b/src/Cli/dotnet/Commands/Workload/WorkloadIntegrityChecker.cs
@@ -38,7 +38,11 @@ public static void RunFirstUseCheck(IReporter reporter)
if (installedWorkloads.Any())
{
reporter.WriteLine(CliCommandStrings.WorkloadIntegrityCheck);
- CliTransaction.RunNew(context => installer.InstallWorkloads(installedWorkloads, sdkFeatureBand, context));
+ CliTransaction.RunNew(context => installer.InstallWorkloads(
+ installedWorkloads,
+ sdkFeatureBand,
+ context,
+ ProcessLifecycle.CancellationToken));
reporter.WriteLine("----------------");
}
}
diff --git a/src/Cli/dotnet/Commands/Workload/WorkloadManifestCorruptionRepairer.cs b/src/Cli/dotnet/Commands/Workload/WorkloadManifestCorruptionRepairer.cs
index 28bfe766a5f0..124f6279f6ba 100644
--- a/src/Cli/dotnet/Commands/Workload/WorkloadManifestCorruptionRepairer.cs
+++ b/src/Cli/dotnet/Commands/Workload/WorkloadManifestCorruptionRepairer.cs
@@ -93,7 +93,10 @@ private void RepairCorruptWorkloadSet(ITransactionContext context, WorkloadSet w
foreach (var manifestUpdate in manifestUpdates)
{
- _workloadInstaller.InstallWorkloadManifest(manifestUpdate, context);
+ _workloadInstaller.InstallWorkloadManifest(
+ manifestUpdate,
+ context,
+ ProcessLifecycle.CancellationToken);
}
}
diff --git a/src/Cli/dotnet/FilePermissionSetter.cs b/src/Cli/dotnet/FilePermissionSetter.cs
index 4b1ee8216b23..fc271612dd93 100644
--- a/src/Cli/dotnet/FilePermissionSetter.cs
+++ b/src/Cli/dotnet/FilePermissionSetter.cs
@@ -9,9 +9,9 @@ namespace Microsoft.DotNet.Cli;
internal class FilePermissionSetter : IFilePermissionSetter
{
- public void SetUserExecutionPermission(string path)
+ public void SetUserExecutionPermission(string path, CancellationToken cancellationToken)
{
- RunCommand(path, "u+x");
+ RunCommand(path, "u+x", cancellationToken);
}
///
@@ -19,12 +19,12 @@ public void SetUserExecutionPermission(string path)
/// (G)roup can read, can't write and can execute.
/// (O)thers can read, can't write and can execute.
///
- public void SetPermission(string path, string chmodArgument)
+ public void SetPermission(string path, string chmodArgument, CancellationToken cancellationToken)
{
- RunCommand(path, chmodArgument.ToString());
+ RunCommand(path, chmodArgument.ToString(), cancellationToken);
}
- private static void RunCommand(string path, string chmodArgument)
+ private static void RunCommand(string path, string chmodArgument, CancellationToken cancellationToken)
{
if (OperatingSystem.IsWindows())
{
@@ -35,7 +35,7 @@ private static void RunCommand(string path, string chmodArgument)
.Create("chmod", [chmodArgument, path])
.CaptureStdOut()
.CaptureStdErr()
- .Execute();
+ .Execute(cancellationToken);
if (result.ExitCode != 0)
{
diff --git a/src/Cli/dotnet/FirstRunExperience.cs b/src/Cli/dotnet/FirstRunExperience.cs
index 25044b7b4126..2ae6bd9d098d 100644
--- a/src/Cli/dotnet/FirstRunExperience.cs
+++ b/src/Cli/dotnet/FirstRunExperience.cs
@@ -152,7 +152,7 @@ public static bool Setup(ParseResult parseResult)
{
WorkloadIntegrityChecker.RunFirstUseCheck(reporter);
}
- catch (Exception)
+ catch (Exception ex) when (ex is not OperationCanceledException)
{
// If the workload check fails for any reason, we want to eat the failure and continue running the command.
reporter.WriteLine(CliStrings.WorkloadIntegrityCheckError.Yellow());
diff --git a/src/Cli/dotnet/ForwardingApp.cs b/src/Cli/dotnet/ForwardingApp.cs
index e0382f781d35..2daabcad4a82 100644
--- a/src/Cli/dotnet/ForwardingApp.cs
+++ b/src/Cli/dotnet/ForwardingApp.cs
@@ -35,8 +35,8 @@ public ForwardingApp WithEnvironmentVariable(string name, string value)
return this;
}
- public int Execute()
+ public int Execute(CancellationToken cancellationToken)
{
- return _implementation.Execute();
+ return _implementation.Execute(cancellationToken);
}
}
diff --git a/src/Cli/dotnet/ICommandRunner.cs b/src/Cli/dotnet/ICommandRunner.cs
index 1f88b750a8ba..65d9b82c7fcb 100644
--- a/src/Cli/dotnet/ICommandRunner.cs
+++ b/src/Cli/dotnet/ICommandRunner.cs
@@ -7,5 +7,5 @@ namespace Microsoft.DotNet.Cli;
public interface ICommandRunner
{
- int Run(string[] commandArgs);
+ int Run(string[] commandArgs, CancellationToken cancellationToken);
}
diff --git a/src/Cli/dotnet/IFilePermissionSetter.cs b/src/Cli/dotnet/IFilePermissionSetter.cs
index 17909ffc54de..55a985e6b893 100644
--- a/src/Cli/dotnet/IFilePermissionSetter.cs
+++ b/src/Cli/dotnet/IFilePermissionSetter.cs
@@ -7,6 +7,6 @@ namespace Microsoft.DotNet.Cli;
internal interface IFilePermissionSetter
{
- void SetUserExecutionPermission(string path);
- void SetPermission(string path, string chmodArgument);
+ void SetUserExecutionPermission(string path, CancellationToken cancellationToken);
+ void SetPermission(string path, string chmodArgument, CancellationToken cancellationToken);
}
diff --git a/src/Cli/dotnet/NuGetForwardingApp.cs b/src/Cli/dotnet/NuGetForwardingApp.cs
index a3aeae4d6da5..08de64342476 100644
--- a/src/Cli/dotnet/NuGetForwardingApp.cs
+++ b/src/Cli/dotnet/NuGetForwardingApp.cs
@@ -21,13 +21,13 @@ public NuGetForwardingApp(IEnumerable argsToForward)
NuGetSignatureVerificationEnabler.ConditionallyEnable(_forwardingApp);
}
- public int Execute()
+ public int Execute(CancellationToken cancellationToken)
{
// Ignore Ctrl-C for the remainder of the command's execution
// Forwarding commands will just spawn the child process and exit
Console.CancelKeyPress += (sender, e) => { e.Cancel = true; };
- return _forwardingApp.Execute();
+ return _forwardingApp.Execute(cancellationToken);
}
public NuGetForwardingApp WithEnvironmentVariable(string name, string value)
diff --git a/src/Cli/dotnet/NugetPackageDownloader/FirstPartyNuGetPackageSigningVerifier.cs b/src/Cli/dotnet/NugetPackageDownloader/FirstPartyNuGetPackageSigningVerifier.cs
index 5f75683b4e80..54b88ef0886d 100644
--- a/src/Cli/dotnet/NugetPackageDownloader/FirstPartyNuGetPackageSigningVerifier.cs
+++ b/src/Cli/dotnet/NugetPackageDownloader/FirstPartyNuGetPackageSigningVerifier.cs
@@ -75,9 +75,10 @@ public FirstPartyNuGetPackageSigningVerifier()
/// Path to the .nupkg file.
/// Diagnostic output from the NuGet verify command.
/// if the package is validly signed by Microsoft.
- public bool Verify(FilePath nupkgToVerify, out string commandOutput)
+ public bool Verify(FilePath nupkgToVerify, CancellationToken cancellationToken, out string commandOutput)
{
- return NuGetVerify(nupkgToVerify, out commandOutput) && IsFirstParty(nupkgToVerify);
+ return NuGetVerify(nupkgToVerify, cancellationToken, out commandOutput) &&
+ IsFirstParty(nupkgToVerify, cancellationToken);
}
///
@@ -93,13 +94,13 @@ public bool Verify(FilePath nupkgToVerify, out string commandOutput)
/// This does NOT validate the signature itself — only the identity of the signer.
/// Call first for signature validation.
///
- internal bool IsFirstParty(FilePath nupkgToVerify)
+ internal bool IsFirstParty(FilePath nupkgToVerify, CancellationToken cancellationToken)
{
try
{
using (var packageReader = new PackageArchiveReader(nupkgToVerify.Value))
{
- PrimarySignature primarySignature = packageReader.GetPrimarySignatureAsync(CancellationToken.None).GetAwaiter().GetResult();
+ PrimarySignature primarySignature = packageReader.GetPrimarySignatureAsync(cancellationToken).GetAwaiter().GetResult();
using (IX509CertificateChain certificateChain = SignatureUtility.GetCertificateChain(primarySignature))
{
if (certificateChain.Count < 2)
@@ -143,13 +144,17 @@ internal bool IsFirstParty(FilePath nupkgToVerify)
/// Combined stdout + stderr from the verify command.
/// Working directory for NuGet config resolution (optional).
/// if the package signature is valid.
- public static bool NuGetVerify(FilePath nupkgToVerify, out string commandOutput, string currentWorkingDirectory = null)
+ public static bool NuGetVerify(
+ FilePath nupkgToVerify,
+ CancellationToken cancellationToken,
+ out string commandOutput,
+ string currentWorkingDirectory = null)
{
var args = new[] { "verify", "--all", nupkgToVerify.Value };
var command = new DotNetCommandFactory(alwaysRunOutOfProc: true, currentWorkingDirectory)
.Create("nuget", args);
- var commandResult = command.CaptureStdOut().Execute();
+ var commandResult = command.CaptureStdOut().Execute(cancellationToken);
commandOutput = commandResult.StdOut + Environment.NewLine + commandResult.StdErr;
return commandResult.ExitCode == 0;
}
diff --git a/src/Cli/dotnet/NugetPackageDownloader/IFirstPartyNuGetPackageSigningVerifier.cs b/src/Cli/dotnet/NugetPackageDownloader/IFirstPartyNuGetPackageSigningVerifier.cs
index 70a068ee810f..07f93ad21d6b 100644
--- a/src/Cli/dotnet/NugetPackageDownloader/IFirstPartyNuGetPackageSigningVerifier.cs
+++ b/src/Cli/dotnet/NugetPackageDownloader/IFirstPartyNuGetPackageSigningVerifier.cs
@@ -9,5 +9,5 @@ namespace Microsoft.DotNet.Cli.NuGetPackageDownloader;
public interface IFirstPartyNuGetPackageSigningVerifier
{
- bool Verify(FilePath nupkgToVerify, out string commandOutput);
+ bool Verify(FilePath nupkgToVerify, CancellationToken cancellationToken, out string commandOutput);
}
diff --git a/src/Cli/dotnet/NugetPackageDownloader/INuGetPackageDownloader.cs b/src/Cli/dotnet/NugetPackageDownloader/INuGetPackageDownloader.cs
index e77d302a74df..830dada6b20f 100644
--- a/src/Cli/dotnet/NugetPackageDownloader/INuGetPackageDownloader.cs
+++ b/src/Cli/dotnet/NugetPackageDownloader/INuGetPackageDownloader.cs
@@ -13,6 +13,7 @@ namespace Microsoft.DotNet.Cli.NuGetPackageDownloader;
internal interface INuGetPackageDownloader
{
Task DownloadPackageAsync(PackageId packageId,
+ CancellationToken cancellationToken,
NuGetVersion packageVersion = null,
PackageSourceLocation packageSourceLocation = null,
bool includePreview = false,
@@ -21,27 +22,31 @@ Task DownloadPackageAsync(PackageId packageId,
PackageSourceMapping packageSourceMapping = null);
Task GetPackageUrl(PackageId packageId,
+ CancellationToken cancellationToken,
NuGetVersion packageVersion = null,
PackageSourceLocation packageSourceLocation = null,
bool includePreview = false);
- Task> ExtractPackageAsync(string packagePath, DirectoryPath targetFolder);
+ Task> ExtractPackageAsync(string packagePath, DirectoryPath targetFolder, CancellationToken cancellationToken);
Task GetLatestPackageVersion(PackageId packageId,
+ CancellationToken cancellationToken,
PackageSourceLocation packageSourceLocation = null,
bool includePreview = false);
Task> GetLatestPackageVersions(PackageId packageId,
int numberOfResults,
+ CancellationToken cancellationToken,
PackageSourceLocation packageSourceLocation = null,
bool includePreview = false);
Task GetBestPackageVersionAsync(PackageId packageId,
VersionRange versionRange,
+ CancellationToken cancellationToken,
PackageSourceLocation packageSourceLocation = null);
Task<(NuGetVersion version, PackageSource source)> GetBestPackageVersionAndSourceAsync(PackageId packageId,
VersionRange versionRange,
- PackageSourceLocation packageSourceLocation = null,
- CancellationToken cancellationToken = default);
+ CancellationToken cancellationToken,
+ PackageSourceLocation packageSourceLocation = null);
}
diff --git a/src/Cli/dotnet/NugetPackageDownloader/NuGetPackageDownloader.cs b/src/Cli/dotnet/NugetPackageDownloader/NuGetPackageDownloader.cs
index baba57170c17..7256d048c349 100644
--- a/src/Cli/dotnet/NugetPackageDownloader/NuGetPackageDownloader.cs
+++ b/src/Cli/dotnet/NugetPackageDownloader/NuGetPackageDownloader.cs
@@ -158,6 +158,7 @@ public static NuGetPackageDownloader CreateForWorkloads(
}
public async Task DownloadPackageAsync(PackageId packageId,
+ CancellationToken cancellationToken,
NuGetVersion packageVersion = null,
PackageSourceLocation packageSourceLocation = null,
bool includePreview = false,
@@ -165,10 +166,14 @@ public async Task DownloadPackageAsync(PackageId packageId,
DirectoryPath? downloadFolder = null,
PackageSourceMapping packageSourceMapping = null)
{
- CancellationToken cancellationToken = CancellationToken.None;
-
- (var source, var resolvedPackageVersion) = await GetPackageSourceAndVersion(packageId, packageVersion,
- packageSourceLocation, includePreview, includeUnlisted ?? packageVersion is not null, packageSourceMapping).ConfigureAwait(false);
+ (var source, var resolvedPackageVersion) = await GetPackageSourceAndVersion(
+ packageId,
+ cancellationToken,
+ packageVersion,
+ packageSourceLocation,
+ includePreview,
+ includeUnlisted ?? packageVersion is not null,
+ packageSourceMapping).ConfigureAwait(false);
FindPackageByIdResource resource = null;
SourceRepository repository = GetSourceRepository(source);
@@ -199,7 +204,9 @@ public async Task DownloadPackageAsync(PackageId packageId,
destinationStream,
_cacheSettings,
_verboseLogger,
- cancellationToken));
+ cancellationToken),
+ cancellationToken,
+ timer: _retryTimer ?? (() => ExponentialRetry.Timer(ExponentialRetry.Intervals, cancellationToken)));
destinationStream.Close();
if (!success)
@@ -212,7 +219,7 @@ public async Task DownloadPackageAsync(PackageId packageId,
// Delete file if verification fails
try
{
- await VerifySigning(nupkgPath, repository);
+ await VerifySigning(nupkgPath, repository, cancellationToken);
}
catch (NuGetPackageInstallerException)
{
@@ -252,7 +259,7 @@ private bool VerbosityGreaterThanMinimal() =>
///
/// Full path to the downloaded .nupkg file.
/// The NuGet source repository the package was downloaded from.
- private async Task VerifySigning(string nupkgPath, SourceRepository repository)
+ private async Task VerifySigning(string nupkgPath, SourceRepository repository, CancellationToken cancellationToken)
{
if (!_verifySignatures && !_validationMessagesDisplayed)
{
@@ -269,7 +276,7 @@ private async Task VerifySigning(string nupkgPath, SourceRepository repository)
}
if (repository is not null &&
- await repository.GetResourceAsync().ConfigureAwait(false) is RepositorySignatureResource resource &&
+ await repository.GetResourceAsync(cancellationToken).ConfigureAwait(false) is RepositorySignatureResource resource &&
resource.AllRepositorySigned)
{
string commandOutput;
@@ -281,8 +288,8 @@ await repository.GetResourceAsync().ConfigureAwait(
//
// With source mapping: NuGetVerify() = valid NuGet signature (any trusted signer)
// -> Package source mapping already constrains feeds, so first-party requirement is relaxed.
- if ((!_shouldUsePackageSourceMapping && !_firstPartyNuGetPackageSigningVerifier.Verify(new FilePath(nupkgPath), out commandOutput)) ||
- (_shouldUsePackageSourceMapping && !FirstPartyNuGetPackageSigningVerifier.NuGetVerify(new FilePath(nupkgPath), out commandOutput, _currentWorkingDirectory)))
+ if ((!_shouldUsePackageSourceMapping && !_firstPartyNuGetPackageSigningVerifier.Verify(new FilePath(nupkgPath), cancellationToken, out commandOutput)) ||
+ (_shouldUsePackageSourceMapping && !FirstPartyNuGetPackageSigningVerifier.NuGetVerify(new FilePath(nupkgPath), cancellationToken, out commandOutput, _currentWorkingDirectory)))
{
throw new NuGetPackageInstallerException(string.Format(CliStrings.FailedToValidatePackageSigning, commandOutput));
}
@@ -300,11 +307,12 @@ await repository.GetResourceAsync().ConfigureAwait(
}
public async Task GetPackageUrl(PackageId packageId,
+ CancellationToken cancellationToken,
NuGetVersion packageVersion = null,
PackageSourceLocation packageSourceLocation = null,
bool includePreview = false)
{
- (var source, var resolvedPackageVersion) = await GetPackageSourceAndVersion(packageId, packageVersion, packageSourceLocation, includePreview).ConfigureAwait(false);
+ (var source, var resolvedPackageVersion) = await GetPackageSourceAndVersion(packageId, cancellationToken, packageVersion, packageSourceLocation, includePreview).ConfigureAwait(false);
SourceRepository repository = GetSourceRepository(source);
if (repository.PackageSource.IsLocal)
@@ -315,14 +323,17 @@ public async Task GetPackageUrl(PackageId packageId,
);
}
- ServiceIndexResourceV3 serviceIndexResource = repository.GetResourceAsync().Result;
+ ServiceIndexResourceV3 serviceIndexResource = await repository.GetResourceAsync(cancellationToken).ConfigureAwait(false);
IReadOnlyList packageBaseAddress =
serviceIndexResource?.GetServiceEntryUris(ServiceTypes.PackageBaseAddress);
return GetNupkgUrl(packageBaseAddress[0].ToString(), packageId, resolvedPackageVersion);
}
- public async Task