From 175efca71f5d87d6e85cefd6ebdf37f10500144f Mon Sep 17 00:00:00 2001 From: Next Turn <45985406+NextTurn@users.noreply.github.com> Date: Fri, 27 Mar 2020 02:17:58 +0800 Subject: [PATCH] Fix `Service.cs` to not modify collection while enumerating it (#11851) --- .../commands/management/Service.cs | 24 +++++-------------- 1 file changed, 6 insertions(+), 18 deletions(-) diff --git a/src/Microsoft.PowerShell.Commands.Management/commands/management/Service.cs b/src/Microsoft.PowerShell.Commands.Management/commands/management/Service.cs index d2468387f1..8081e98c26 100644 --- a/src/Microsoft.PowerShell.Commands.Management/commands/management/Service.cs +++ b/src/Microsoft.PowerShell.Commands.Management/commands/management/Service.cs @@ -1087,17 +1087,9 @@ namespace Microsoft.PowerShell.Commands /// True if all dependent services are stopped /// False if not all dependent services are stopped /// - private bool HaveAllDependentServicesStopped(ICollection dependentServices) + private bool HaveAllDependentServicesStopped(ServiceController[] dependentServices) { - foreach (ServiceController service in dependentServices) - { - if (service.Status != ServiceControllerStatus.Stopped) - { - return false; - } - } - - return true; + return Array.TrueForAll(dependentServices, service => service.Status == ServiceControllerStatus.Stopped); } /// @@ -1106,14 +1098,10 @@ namespace Microsoft.PowerShell.Commands /// A list of services. internal void RemoveNotStoppedServices(List services) { - foreach (ServiceController service in services) - { - if (service.Status != ServiceControllerStatus.Stopped && - service.Status != ServiceControllerStatus.StopPending) - { - services.Remove(service); - } - } + // You shall not modify a collection during enumeration. + services.RemoveAll(service => + service.Status != ServiceControllerStatus.Stopped && + service.Status != ServiceControllerStatus.StopPending); } ///