forked from PowerShell/PowerShell
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPSTask.cs
More file actions
1593 lines (1318 loc) · 51.8 KB
/
Copy pathPSTask.cs
File metadata and controls
1593 lines (1318 loc) · 51.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Globalization;
using System.Management.Automation.Host;
using System.Management.Automation.Language;
using System.Management.Automation.Remoting.Internal;
using System.Management.Automation.Runspaces;
using System.Management.Automation.Security;
using System.Threading;
using Dbg = System.Management.Automation.Diagnostics;
namespace System.Management.Automation.PSTasks
{
#region PSTask
/// <summary>
/// Class to encapsulate synchronous running scripts in parallel.
/// </summary>
internal sealed class PSTask : PSTaskBase
{
#region Members
private readonly PSTaskDataStreamWriter _dataStreamWriter;
#endregion
#region Constructor
/// <summary>
/// Initializes a new instance of the <see cref="PSTask"/> class.
/// </summary>
/// <param name="scriptBlock">Script block to run in task.</param>
/// <param name="usingValuesMap">Using values passed into script block.</param>
/// <param name="dollarUnderbar">Dollar underbar variable value.</param>
/// <param name="currentLocationPath">Current working directory.</param>
/// <param name="dataStreamWriter">Cmdlet data stream writer.</param>
public PSTask(
ScriptBlock scriptBlock,
Dictionary<string, object> usingValuesMap,
object dollarUnderbar,
string currentLocationPath,
PSTaskDataStreamWriter dataStreamWriter)
: base(
scriptBlock,
usingValuesMap,
dollarUnderbar,
currentLocationPath)
{
_dataStreamWriter = dataStreamWriter;
}
#endregion
#region Overrides
/// <summary>
/// Initialize PowerShell object.
/// </summary>
protected override void InitializePowershell()
{
// Writer data stream handlers
_output.DataAdded += (sender, args) => HandleOutputData();
_powershell.Streams.Error.DataAdded += (sender, args) => HandleErrorData();
_powershell.Streams.Warning.DataAdded += (sender, args) => HandleWarningData();
_powershell.Streams.Verbose.DataAdded += (sender, args) => HandleVerboseData();
_powershell.Streams.Debug.DataAdded += (sender, args) => HandleDebugData();
_powershell.Streams.Progress.DataAdded += (sender, args) => HandleProgressData();
_powershell.Streams.Information.DataAdded += (sender, args) => HandleInformationData();
// State change handler
_powershell.InvocationStateChanged += (sender, args) => HandleStateChanged(args);
}
#endregion
#region Writer data stream handlers
private void HandleOutputData()
{
foreach (var item in _output.ReadAll())
{
_dataStreamWriter.Add(
new PSStreamObject(PSStreamObjectType.Output, item));
}
}
private void HandleErrorData()
{
foreach (var item in _powershell.Streams.Error.ReadAll())
{
_dataStreamWriter.Add(
new PSStreamObject(PSStreamObjectType.Error, item));
}
}
private void HandleWarningData()
{
foreach (var item in _powershell.Streams.Warning.ReadAll())
{
_dataStreamWriter.Add(
new PSStreamObject(PSStreamObjectType.Warning, item.Message));
}
}
private void HandleVerboseData()
{
foreach (var item in _powershell.Streams.Verbose.ReadAll())
{
_dataStreamWriter.Add(
new PSStreamObject(PSStreamObjectType.Verbose, item.Message));
}
}
private void HandleDebugData()
{
foreach (var item in _powershell.Streams.Debug.ReadAll())
{
_dataStreamWriter.Add(
new PSStreamObject(PSStreamObjectType.Debug, item.Message));
}
}
private void HandleInformationData()
{
foreach (var item in _powershell.Streams.Information.ReadAll())
{
_dataStreamWriter.Add(
new PSStreamObject(PSStreamObjectType.Information, item));
}
}
private void HandleProgressData()
{
foreach (var item in _powershell.Streams.Progress.ReadAll())
{
_dataStreamWriter.Add(
new PSStreamObject(PSStreamObjectType.Progress, item));
}
}
#endregion
#region Event handlers
private void HandleStateChanged(PSInvocationStateChangedEventArgs stateChangeInfo)
{
if (_dataStreamWriter != null)
{
// Treat any terminating exception as a non-terminating error record
var newStateInfo = stateChangeInfo.InvocationStateInfo;
if (newStateInfo.Reason != null)
{
var errorRecord = new ErrorRecord(
newStateInfo.Reason,
"PSTaskException",
ErrorCategory.InvalidOperation,
this);
_dataStreamWriter.Add(
new PSStreamObject(PSStreamObjectType.Error, errorRecord));
}
}
RaiseStateChangedEvent(stateChangeInfo);
}
#endregion
}
/// <summary>
/// Class to encapsulate asynchronous running scripts in parallel as jobs.
/// </summary>
internal sealed class PSJobTask : PSTaskBase
{
#region Members
private readonly Job _job;
#endregion
#region Constructor
/// <summary>
/// Initializes a new instance of the <see cref="PSJobTask"/> class.
/// </summary>
/// <param name="scriptBlock">Script block to run.</param>
/// <param name="usingValuesMap">Using variable values passed to script block.</param>
/// <param name="dollarUnderbar">Dollar underbar variable value for script block.</param>
/// <param name="currentLocationPath">Current working directory.</param>
/// <param name="job">Job object associated with task.</param>
public PSJobTask(
ScriptBlock scriptBlock,
Dictionary<string, object> usingValuesMap,
object dollarUnderbar,
string currentLocationPath,
Job job) : base(
scriptBlock,
usingValuesMap,
dollarUnderbar,
currentLocationPath)
{
_job = job;
}
#endregion
#region Overrides
/// <summary>
/// Initialize PowerShell object.
/// </summary>
protected override void InitializePowershell()
{
// Job data stream handlers
_output.DataAdded += (sender, args) => HandleJobOutputData();
_powershell.Streams.Error.DataAdded += (sender, args) => HandleJobErrorData();
_powershell.Streams.Warning.DataAdded += (sender, args) => HandleJobWarningData();
_powershell.Streams.Verbose.DataAdded += (sender, args) => HandleJobVerboseData();
_powershell.Streams.Debug.DataAdded += (sender, args) => HandleJobDebugData();
_powershell.Streams.Information.DataAdded += (sender, args) => HandleJobInformationData();
// State change handler
_powershell.InvocationStateChanged += (sender, args) => HandleStateChanged(args);
}
#endregion
#region Job data stream handlers
private void HandleJobOutputData()
{
foreach (var item in _output.ReadAll())
{
_job.Output.Add(item);
_job.Results.Add(
new PSStreamObject(PSStreamObjectType.Output, item));
}
}
private void HandleJobErrorData()
{
foreach (var item in _powershell.Streams.Error.ReadAll())
{
_job.Error.Add(item);
_job.Results.Add(
new PSStreamObject(PSStreamObjectType.Error, item));
}
}
private void HandleJobWarningData()
{
foreach (var item in _powershell.Streams.Warning.ReadAll())
{
_job.Warning.Add(item);
_job.Results.Add(
new PSStreamObject(PSStreamObjectType.Warning, item.Message));
}
}
private void HandleJobVerboseData()
{
foreach (var item in _powershell.Streams.Verbose.ReadAll())
{
_job.Verbose.Add(item);
_job.Results.Add(
new PSStreamObject(PSStreamObjectType.Verbose, item.Message));
}
}
private void HandleJobDebugData()
{
foreach (var item in _powershell.Streams.Debug.ReadAll())
{
_job.Debug.Add(item);
_job.Results.Add(
new PSStreamObject(PSStreamObjectType.Debug, item.Message));
}
}
private void HandleJobInformationData()
{
foreach (var item in _powershell.Streams.Information.ReadAll())
{
_job.Information.Add(item);
_job.Results.Add(
new PSStreamObject(PSStreamObjectType.Information, item));
}
}
#endregion
#region Event handlers
private void HandleStateChanged(PSInvocationStateChangedEventArgs stateChangeInfo)
{
RaiseStateChangedEvent(stateChangeInfo);
}
#endregion
#region Properties
/// <summary>
/// Gets Debugger.
/// </summary>
public Debugger Debugger
{
get => _powershell.Runspace.Debugger;
}
#endregion
}
/// <summary>
/// Base class to encapsulate running a PowerShell script concurrently in a cmdlet or job context.
/// </summary>
internal abstract class PSTaskBase : IDisposable
{
#region Members
private readonly ScriptBlock _scriptBlockToRun;
private readonly Dictionary<string, object> _usingValuesMap;
private readonly object _dollarUnderbar;
private readonly int _id;
private readonly string _currentLocationPath;
private Runspace _runspace;
protected PowerShell _powershell;
protected PSDataCollection<PSObject> _output;
public const string RunspaceName = "PSTask";
private static int s_taskId;
#endregion
#region Events
/// <summary>
/// Event that fires when the task running state changes.
/// </summary>
public event EventHandler<PSInvocationStateChangedEventArgs> StateChanged;
internal void RaiseStateChangedEvent(PSInvocationStateChangedEventArgs args)
{
StateChanged.SafeInvoke(this, args);
}
#endregion
#region Properties
/// <summary>
/// Gets current running state of the task.
/// </summary>
public PSInvocationState State
{
get
{
PowerShell ps = _powershell;
if (ps != null)
{
return ps.InvocationStateInfo.State;
}
return PSInvocationState.NotStarted;
}
}
/// <summary>
/// Gets Task Id.
/// </summary>
public int Id { get => _id; }
/// <summary>
/// Gets Task Runspace.
/// </summary>
public Runspace Runspace { get => _runspace; }
#endregion
#region Constructor
private PSTaskBase()
{
_id = Interlocked.Increment(ref s_taskId);
}
/// <summary>
/// Initializes a new instance of the <see cref="PSTaskBase"/> class.
/// </summary>
/// <param name="scriptBlock">Script block to run.</param>
/// <param name="usingValuesMap">Using variable values passed to script block.</param>
/// <param name="dollarUnderbar">Dollar underbar variable value.</param>
/// <param name="currentLocationPath">Current working directory.</param>
protected PSTaskBase(
ScriptBlock scriptBlock,
Dictionary<string, object> usingValuesMap,
object dollarUnderbar,
string currentLocationPath) : this()
{
_scriptBlockToRun = scriptBlock;
_usingValuesMap = usingValuesMap;
_dollarUnderbar = dollarUnderbar;
_currentLocationPath = currentLocationPath;
}
#endregion
#region Abstract Methods
/// <summary>
/// Initialize PowerShell object.
/// </summary>
protected abstract void InitializePowershell();
#endregion
#region IDisposable
/// <summary>
/// Dispose PSTaskBase instance.
/// </summary>
public void Dispose()
{
_powershell.Dispose();
_output.Dispose();
}
#endregion
#region Public Methods
/// <summary>
/// Start task.
/// </summary>
/// <param name="runspace">Runspace used to run task.</param>
public void Start(Runspace runspace)
{
if (_powershell != null)
{
Dbg.Assert(false, "A PSTask can be started only once.");
return;
}
Dbg.Assert(runspace != null, "Task runspace cannot be null.");
_runspace = runspace;
// If available, set current working directory on the runspace.
// Temporarily set the newly created runspace as the thread default runspace for any needed module loading.
if (_currentLocationPath != null)
{
var oldDefaultRunspace = Runspace.DefaultRunspace;
try
{
Runspace.DefaultRunspace = runspace;
var context = new CmdletProviderContext(runspace.ExecutionContext)
{
// _currentLocationPath denotes the current path as-is, and should not be attempted expanded.
SuppressWildcardExpansion = true
};
runspace.ExecutionContext.SessionState.Internal.SetLocation(_currentLocationPath, context);
}
catch (DriveNotFoundException)
{
// Allow task to run if current drive is not available.
}
finally
{
Runspace.DefaultRunspace = oldDefaultRunspace;
}
}
// Create the PowerShell command pipeline for the provided script block
// The script will run on the provided Runspace in a new thread by default
_powershell = PowerShell.Create(runspace);
// Initialize PowerShell object data streams and event handlers
_output = new PSDataCollection<PSObject>();
InitializePowershell();
// Start the script running in a new thread
_powershell.AddScript(_scriptBlockToRun.ToString());
_powershell.Commands.Commands[0].DollarUnderbar = _dollarUnderbar;
if (_usingValuesMap != null && _usingValuesMap.Count > 0)
{
_powershell.AddParameter(Parser.VERBATIM_ARGUMENT, _usingValuesMap);
}
_powershell.BeginInvoke<object, PSObject>(input: null, output: _output);
}
/// <summary>
/// Signals the running task to stop.
/// </summary>
public void SignalStop() => _powershell?.BeginStop(null, null);
#endregion
}
#endregion
#region PSTaskDataStreamWriter
/// <summary>
/// Class that handles writing task data stream objects to a cmdlet.
/// </summary>
internal sealed class PSTaskDataStreamWriter : IDisposable
{
#region Members
private readonly PSCmdlet _cmdlet;
private readonly PSDataCollection<PSStreamObject> _dataStream;
private readonly int _cmdletThreadId;
#endregion
#region Properties
/// <summary>
/// Gets wait-able handle that signals when new data has been added to
/// the data stream collection.
/// </summary>
/// <returns>Data added wait handle.</returns>
internal WaitHandle DataAddedWaitHandle
{
get => _dataStream.WaitHandle;
}
#endregion
#region Constructor
private PSTaskDataStreamWriter() { }
/// <summary>
/// Initializes a new instance of the <see cref="PSTaskDataStreamWriter"/> class.
/// </summary>
/// <param name="psCmdlet">Parent cmdlet.</param>
public PSTaskDataStreamWriter(PSCmdlet psCmdlet)
{
_cmdlet = psCmdlet;
_cmdletThreadId = Environment.CurrentManagedThreadId;
_dataStream = new PSDataCollection<PSStreamObject>();
}
#endregion
#region Public Methods
/// <summary>
/// Add data stream object to the writer.
/// </summary>
/// <param name="streamObject">Data stream object to write.</param>
public void Add(PSStreamObject streamObject)
{
_dataStream.Add(streamObject);
}
/// <summary>
/// Write all objects in data stream collection to the cmdlet data stream.
/// </summary>
public void WriteImmediate()
{
CheckCmdletThread();
foreach (var item in _dataStream.ReadAll())
{
item.WriteStreamObject(cmdlet: _cmdlet, overrideInquire: true);
}
}
/// <summary>
/// Waits for data stream objects to be added to the collection, and writes them
/// to the cmdlet data stream.
/// This method returns only after the writer has been closed.
/// </summary>
public void WaitAndWrite()
{
CheckCmdletThread();
while (true)
{
_dataStream.WaitHandle.WaitOne();
WriteImmediate();
if (!_dataStream.IsOpen)
{
WriteImmediate();
break;
}
}
}
/// <summary>
/// Closes the stream writer.
/// </summary>
public void Close()
{
_dataStream.Complete();
}
#endregion
#region Private Methods
private void CheckCmdletThread()
{
if (Environment.CurrentManagedThreadId != _cmdletThreadId)
{
throw new PSInvalidOperationException(InternalCommandStrings.PSTaskStreamWriterWrongThread);
}
}
#endregion
#region IDisposable
/// <summary>
/// Dispose the stream writer.
/// </summary>
public void Dispose()
{
_dataStream.Dispose();
}
#endregion
}
#endregion
#region PSTaskPool
/// <summary>
/// Pool for running PSTasks, with limit of total number of running tasks at a time.
/// </summary>
internal sealed class PSTaskPool : IDisposable
{
#region Members
private readonly ManualResetEvent _addAvailable;
private readonly int _sizeLimit;
private readonly ManualResetEvent _stopAll;
private readonly object _syncObject;
private readonly Dictionary<int, PSTaskBase> _taskPool;
private readonly ConcurrentQueue<Runspace> _runspacePool;
private readonly ConcurrentDictionary<int, Runspace> _activeRunspaces;
private readonly WaitHandle[] _waitHandles;
private readonly bool _useRunspacePool;
private bool _isOpen;
private bool _stopping;
private int _createdRunspaceCount;
private const int AddAvailable = 0;
private const int Stop = 1;
#endregion
#region Constructor
private PSTaskPool() { }
/// <summary>
/// Initializes a new instance of the <see cref="PSTaskPool"/> class.
/// </summary>
/// <param name="size">Total number of allowed running objects in pool at one time.</param>
/// <param name="useNewRunspace">When true, a new runspace object is created for the task instead of reusing one from the pool.</param>
public PSTaskPool(
int size,
bool useNewRunspace)
{
_sizeLimit = size;
_useRunspacePool = !useNewRunspace;
_isOpen = true;
_syncObject = new object();
_addAvailable = new ManualResetEvent(true);
_stopAll = new ManualResetEvent(false);
_waitHandles = new WaitHandle[]
{
_addAvailable, // index 0
_stopAll, // index 1
};
_taskPool = new Dictionary<int, PSTaskBase>(size);
_activeRunspaces = new ConcurrentDictionary<int, Runspace>();
if (_useRunspacePool)
{
_runspacePool = new ConcurrentQueue<Runspace>();
}
}
#endregion
#region Events
/// <summary>
/// Event that fires when pool is closed and drained of all tasks.
/// </summary>
public event EventHandler<EventArgs> PoolComplete;
#endregion
#region Properties
/// <summary>
/// Gets a value indicating whether a pool is currently open for accepting tasks.
/// </summary>
public bool IsOpen
{
get => _isOpen;
}
/// <summary>
/// Gets a value of the count of total runspaces allocated.
/// </summary>
public int AllocatedRunspaceCount
{
get => _createdRunspaceCount;
}
#endregion
#region IDisposable
/// <summary>
/// Dispose task pool.
/// </summary>
public void Dispose()
{
_addAvailable.Dispose();
_stopAll.Dispose();
DisposeRunspaces();
}
/// <summary>
/// Dispose runspaces.
/// </summary>
internal void DisposeRunspaces()
{
foreach (var item in _activeRunspaces)
{
item.Value.Dispose();
}
_activeRunspaces.Clear();
}
#endregion
#region Public Methods
/// <summary>
/// Method to add a task to the pool.
/// If the pool is full, then this method blocks until space is available.
/// This method is not multi-thread safe and assumes only one thread waits and adds tasks.
/// </summary>
/// <param name="task">Task to be added to pool.</param>
/// <returns>True when task is successfully added.</returns>
public bool Add(PSTaskBase task)
{
if (!_isOpen)
{
return false;
}
// Block until either space is available, or a stop is commanded
var index = WaitHandle.WaitAny(_waitHandles);
switch (index)
{
case AddAvailable:
var runspace = GetRunspace(task.Id);
task.StateChanged += HandleTaskStateChangedDelegate;
lock (_syncObject)
{
if (!_isOpen)
{
return false;
}
_taskPool.Add(task.Id, task);
if (_taskPool.Count == _sizeLimit)
{
_addAvailable.Reset();
}
task.Start(runspace);
}
return true;
case Stop:
return false;
default:
return false;
}
}
/// <summary>
/// Add child job task to task pool.
/// </summary>
/// <param name="childJob">Child job to be added to pool.</param>
/// <returns>True when child job is successfully added.</returns>
public bool Add(PSTaskChildJob childJob)
{
return Add(childJob.Task);
}
/// <summary>
/// Signals all running tasks to stop and closes pool for any new tasks.
/// </summary>
public void StopAll()
{
_stopping = true;
// Accept no more input
Close();
_stopAll.Set();
// Stop all running tasks
PSTaskBase[] tasksToStop;
lock (_syncObject)
{
tasksToStop = new PSTaskBase[_taskPool.Values.Count];
_taskPool.Values.CopyTo(tasksToStop, 0);
}
foreach (var task in tasksToStop)
{
task.Dispose();
}
// Dispose all active runspaces
DisposeRunspaces();
_stopping = false;
}
/// <summary>
/// Closes the pool and prevents any new tasks from being added.
/// </summary>
public void Close()
{
_isOpen = false;
CheckForComplete();
}
#endregion
#region Private Methods
private void HandleTaskStateChangedDelegate(object sender, PSInvocationStateChangedEventArgs args) => HandleTaskStateChanged(sender, args);
private void HandleTaskStateChanged(object sender, PSInvocationStateChangedEventArgs args)
{
var task = sender as PSTaskBase;
Dbg.Assert(task != null, "State changed sender must always be PSTaskBase");
var stateInfo = args.InvocationStateInfo;
switch (stateInfo.State)
{
// Look for completed state and remove
case PSInvocationState.Completed:
case PSInvocationState.Stopped:
case PSInvocationState.Failed:
ReturnRunspace(task);
lock (_syncObject)
{
_taskPool.Remove(task.Id);
if (_taskPool.Count == (_sizeLimit - 1))
{
_addAvailable.Set();
}
}
task.StateChanged -= HandleTaskStateChangedDelegate;
if (!_stopping || stateInfo.State != PSInvocationState.Stopped)
{
// StopAll disposes tasks.
task.Dispose();
}
CheckForComplete();
break;
}
}
private void CheckForComplete()
{
bool isTaskPoolComplete;
lock (_syncObject)
{
isTaskPoolComplete = !_isOpen && _taskPool.Count == 0;
}
if (isTaskPoolComplete)
{
try
{
PoolComplete.SafeInvoke(
this,
new EventArgs());
}
catch
{
Dbg.Assert(false, "Exceptions should not be thrown on event thread");
}
}
}
private Runspace GetRunspace(int taskId)
{
var runspaceName = string.Create(CultureInfo.InvariantCulture, $"{PSTask.RunspaceName}:{taskId}");
if (_useRunspacePool && _runspacePool.TryDequeue(out Runspace runspace))
{
if (runspace.RunspaceStateInfo.State == RunspaceState.Opened &&
runspace.RunspaceAvailability == RunspaceAvailability.Available)
{
try
{
runspace.ResetRunspaceState();
runspace.Name = runspaceName;
return runspace;
}
catch
{
// If the runspace cannot be reset for any reason, remove it.
}
}
RemoveActiveRunspace(runspace);
}
// Create and initialize a new Runspace
var iss = InitialSessionState.CreateDefault2();
switch (SystemPolicy.GetSystemLockdownPolicy())
{
case SystemEnforcementMode.Enforce:
iss.LanguageMode = PSLanguageMode.ConstrainedLanguage;
break;
case SystemEnforcementMode.Audit:
// In audit mode, CL restrictions are not enforced and instead audit
// log entries are created.
iss.LanguageMode = PSLanguageMode.ConstrainedLanguage;
break;
case SystemEnforcementMode.None:
iss.LanguageMode = PSLanguageMode.FullLanguage;
break;
}
runspace = RunspaceFactory.CreateRunspace(iss);
runspace.Name = runspaceName;
_activeRunspaces.TryAdd(runspace.Id, runspace);
runspace.Open();
_createdRunspaceCount++;
return runspace;
}
private void ReturnRunspace(PSTaskBase task)
{
var runspace = task.Runspace;
Dbg.Assert(runspace != null, "Task runspace cannot be null.");
if (_useRunspacePool &&
runspace.RunspaceStateInfo.State == RunspaceState.Opened &&
runspace.RunspaceAvailability == RunspaceAvailability.Available)
{
_runspacePool.Enqueue(runspace);
return;
}
RemoveActiveRunspace(runspace);
}
private void RemoveActiveRunspace(Runspace runspace)
{
runspace.Dispose();
_activeRunspaces.TryRemove(runspace.Id, out Runspace _);
}
#endregion
}
#endregion
#region PSTaskJobs
/// <summary>
/// Job for running ForEach-Object parallel task child jobs asynchronously.
/// </summary>
public sealed class PSTaskJob : Job
{
#region Members
private readonly PSTaskPool _taskPool;