Skip to content

Commit cce214e

Browse files
authored
Implement ForEach-Object -Parallel runspace reuse (PowerShell#12122)
* Implement foreach parallel runspace reuse * Change runspace dispose * Refactor runspace reset check * Fix race condition. * Fix CodFactor issues * Implement -UseNewRunspace parameter switch, add tests * Fix Codacy error
1 parent 7a8094f commit cce214e

3 files changed

Lines changed: 185 additions & 29 deletions

File tree

src/System.Management.Automation/engine/InternalCommands.cs

Lines changed: 11 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -260,6 +260,14 @@ public object[] ArgumentList
260260
[Parameter(ParameterSetName = ForEachObjectCommand.ParallelParameterSet)]
261261
public SwitchParameter AsJob { get; set; }
262262

263+
/// <summary>
264+
/// Gets or sets a flag so that a new runspace object is created for each loop iteration, instead of reusing objects
265+
/// from the runspace pool.
266+
/// By default, runspaces are reused from a runspace pool.
267+
/// </summary>
268+
[Parameter(ParameterSetName = ForEachObjectCommand.ParallelParameterSet)]
269+
public SwitchParameter UseNewRunspace { get; set; }
270+
263271
#endregion
264272

265273
#region Overrides
@@ -437,15 +445,16 @@ private void InitParallelParameterSet()
437445

438446
_taskJob = new PSTaskJob(
439447
Parallel.ToString(),
440-
ThrottleLimit);
448+
ThrottleLimit,
449+
UseNewRunspace);
441450

442451
return;
443452
}
444453

445454
// Set up for synchronous processing and data streaming.
446455
_taskCollection = new PSDataCollection<System.Management.Automation.PSTasks.PSTask>();
447456
_taskDataStreamWriter = new PSTaskDataStreamWriter(this);
448-
_taskPool = new PSTaskPool(ThrottleLimit);
457+
_taskPool = new PSTaskPool(ThrottleLimit, UseNewRunspace);
449458
_taskPool.PoolComplete += (sender, args) =>
450459
{
451460
_taskDataStreamWriter.Close();

0 commit comments

Comments
 (0)