File size: 47,493 Bytes
8c763fb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.

using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Management.Automation.Remoting.Internal;
using System.Threading;

using Dbg = System.Management.Automation.Diagnostics;

namespace System.Management.Automation
{
    internal abstract class StartableJob : Job
    {
        internal StartableJob(string commandName, string jobName)
            : base(commandName, jobName)
        {
        }

        internal abstract void StartJob();
    }

    /// <summary>
    /// A job that can throttle execution of child jobs.
    /// </summary>
    internal sealed class ThrottlingJob : Job
    {
        #region IDisposable Members

        /// <summary>
        /// Releases resources associated with this object.
        /// </summary>
        protected override void Dispose(bool disposing)
        {
            try
            {
                if (disposing)
                {
                    this.StopJob();

                    List<Job> childJobsToDispose;
                    lock (_lockObject)
                    {
                        Dbg.Assert(this.IsFinishedState(this.JobStateInfo.State), "ThrottlingJob should be completed before removing and disposing child jobs");
                        childJobsToDispose = new List<Job>(this.ChildJobs);
                        this.ChildJobs.Clear();
                    }

                    foreach (Job childJob in childJobsToDispose)
                    {
                        childJob.Dispose();
                    }

                    _jobResultsThrottlingSemaphore?.Dispose();
                    _cancellationTokenSource.Dispose();
                }
            }
            finally
            {
                base.Dispose(disposing);
            }
        }

        #endregion

        #region Support for progress reporting

        private readonly DateTime _progressStartTime = DateTime.UtcNow;
        private readonly int _progressActivityId;
        private readonly object _progressLock = new object();
        private DateTime _progressReportLastTime = DateTime.MinValue;

        internal int GetProgressActivityId()
        {
            lock (_progressLock)
            {
                if (_progressReportLastTime.Equals(DateTime.MinValue))
                {
                    try
                    {
                        this.ReportProgress(minimizeFrequentUpdates: false);
                        Dbg.Assert(_progressReportLastTime > DateTime.MinValue, "Progress was reported (lastTimeProgressWasReported)");
                    }
                    catch (PSInvalidOperationException)
                    {
                        // return "no parent activity id" if this ThrottlingJob has already finished
                        return -1;
                    }
                }

                return _progressActivityId;
            }
        }

        private void ReportProgress(bool minimizeFrequentUpdates)
        {
            lock (_progressLock)
            {
                DateTime now = DateTime.UtcNow;

                if (minimizeFrequentUpdates)
                {
                    if ((now - _progressStartTime) < TimeSpan.FromSeconds(1))
                    {
                        return;
                    }

                    if ((!_progressReportLastTime.Equals(DateTime.MinValue)) &&
                        (now - _progressReportLastTime < TimeSpan.FromMilliseconds(200)))
                    {
                        return;
                    }
                }

                _progressReportLastTime = now;

                double workCompleted;
                double totalWork;
                int percentComplete;
                lock (_lockObject)
                {
                    totalWork = _countOfAllChildJobs;
                    workCompleted = this.CountOfFinishedChildJobs;
                }

                if (totalWork >= 1.0)
                {
                    percentComplete = (int)(100.0 * workCompleted / totalWork);
                }
                else
                {
                    percentComplete = -1;
                }

                percentComplete = Math.Max(-1, Math.Min(100, percentComplete));

                var progressRecord = new ProgressRecord(
                    activityId: _progressActivityId,
                    activity: this.Command,
                    statusDescription: this.StatusMessage);

                if (this.IsThrottlingJobCompleted)
                {
                    if (_progressReportLastTime.Equals(DateTime.MinValue))
                    {
                        return;
                    }

                    progressRecord.RecordType = ProgressRecordType.Completed;
                    progressRecord.PercentComplete = 100;
                    progressRecord.SecondsRemaining = 0;
                }
                else
                {
                    progressRecord.RecordType = ProgressRecordType.Processing;
                    progressRecord.PercentComplete = percentComplete;
                    int? secondsRemaining = null;
                    if (percentComplete >= 0)
                    {
                        secondsRemaining = ProgressRecord.GetSecondsRemaining(_progressStartTime, (double)percentComplete / 100.0);
                    }

                    if (secondsRemaining.HasValue)
                    {
                        progressRecord.SecondsRemaining = secondsRemaining.Value;
                    }
                }

                this.WriteProgress(progressRecord);
            }
        }

        #endregion

        /// <summary>
        /// Flags of child jobs of a <see cref="ThrottlingJob"/>
        /// </summary>
        [Flags]
        internal enum ChildJobFlags
        {
            /// <summary>
            /// Child job doesn't have any special properties.
            /// </summary>
            None = 0,

            /// <summary>
            /// Child job can call <see cref="ThrottlingJob.AddChildJobWithoutBlocking"/> method
            /// or <see cref="ThrottlingJob.AddChildJobAndPotentiallyBlock(StartableJob, ChildJobFlags)"/>
            /// or <see cref="ThrottlingJob.AddChildJobAndPotentiallyBlock(Cmdlet, StartableJob, ChildJobFlags)"/>
            /// method
            /// of the <see cref="ThrottlingJob"/> instance it belongs to.
            /// </summary>
            CreatesChildJobs = 0x1,
        }

        private bool _ownerWontSubmitNewChildJobs = false;
        private readonly HashSet<Guid> _setOfChildJobsThatCanAddMoreChildJobs = new HashSet<Guid>();

        private bool IsEndOfChildJobs
        {
            get
            {
                lock (_lockObject)
                {
                    return _isStopping || (_ownerWontSubmitNewChildJobs && _setOfChildJobsThatCanAddMoreChildJobs.Count == 0);
                }
            }
        }

        private bool IsThrottlingJobCompleted
        {
            get
            {
                lock (_lockObject)
                {
                    return this.IsEndOfChildJobs && (_countOfAllChildJobs <= this.CountOfFinishedChildJobs);
                }
            }
        }

        private readonly bool _cmdletMode;

        private int _countOfAllChildJobs;

        private int _countOfBlockedChildJobs;

        private int _countOfFailedChildJobs;
        private int _countOfStoppedChildJobs;
        private int _countOfSuccessfullyCompletedChildJobs;

        private int CountOfFinishedChildJobs
        {
            get
            {
                lock (_lockObject)
                {
                    return _countOfFailedChildJobs + _countOfStoppedChildJobs + _countOfSuccessfullyCompletedChildJobs;
                }
            }
        }

        private int CountOfRunningOrReadyToRunChildJobs
        {
            get
            {
                lock (_lockObject)
                {
                    return _countOfAllChildJobs - this.CountOfFinishedChildJobs;
                }
            }
        }

        private readonly object _lockObject = new object();

        /// <summary>
        /// Creates a new <see cref="ThrottlingJob"/> object.
        /// </summary>
        /// <param name="command">Command invoked by this job object.</param>
        /// <param name="jobName">Friendly name for the job object.</param>
        /// <param name="jobTypeName">Name describing job type.</param>
        /// <param name="maximumConcurrentChildJobs">
        /// The maximum number of child jobs that can be running at any given point in time.
        /// Passing 0 requests to turn off throttling (i.e. allow unlimited number of child jobs to run)
        /// </param>
        /// <param name="cmdletMode">
        /// <see langword="true"/> if this <see cref="ThrottlingJob"/> is used from a cmdlet invoked without -AsJob switch.
        /// <see langword="false"/> if this <see cref="ThrottlingJob"/> is used from a cmdlet invoked with -AsJob switch.
        ///
        /// If <paramref name="cmdletMode"/> is <see langword="true"/>, then
        /// memory can be managed more aggressively (for example ChildJobs can be discarded as soon as they complete)
        /// because the <see cref="ThrottlingJob"/> is not exposed to the end user.
        /// </param>
        internal ThrottlingJob(string command, string jobName, string jobTypeName, int maximumConcurrentChildJobs, bool cmdletMode)
            : base(command, jobName)
        {
            this.Results.BlockingEnumerator = true;
            _cmdletMode = cmdletMode;
            this.PSJobTypeName = jobTypeName;
            if (_cmdletMode)
            {
                _jobResultsThrottlingSemaphore = new SemaphoreSlim(ForwardingHelper.AggregationQueueMaxCapacity);
            }

            _progressActivityId = new Random(this.GetHashCode()).Next();

            this.SetupThrottlingQueue(maximumConcurrentChildJobs);
        }

        internal void AddChildJobAndPotentiallyBlock(
            StartableJob childJob,
            ChildJobFlags flags)
        {
            using (var jobGotEnqueued = new ManualResetEventSlim(initialState: false))
            {
                ArgumentNullException.ThrowIfNull(childJob);

                this.AddChildJobWithoutBlocking(childJob, flags, jobGotEnqueued.Set);
                jobGotEnqueued.Wait();
            }
        }

        internal void AddChildJobAndPotentiallyBlock(
            Cmdlet cmdlet,
            StartableJob childJob,
            ChildJobFlags flags)
        {
            using (var forwardingCancellation = new CancellationTokenSource())
            {
                ArgumentNullException.ThrowIfNull(childJob);

                this.AddChildJobWithoutBlocking(childJob, flags, forwardingCancellation.Cancel);
                this.ForwardAllResultsToCmdlet(cmdlet, forwardingCancellation.Token);
            }
        }

        private bool _alreadyDisabledFlowControlForPendingJobsQueue = false;

        internal void DisableFlowControlForPendingJobsQueue()
        {
            if (!_cmdletMode || _alreadyDisabledFlowControlForPendingJobsQueue)
            {
                return;
            }

            _alreadyDisabledFlowControlForPendingJobsQueue = true;

            lock (_lockObject)
            {
                _maxReadyToRunJobs = int.MaxValue;

                while (_actionsForUnblockingChildAdditions.Count > 0)
                {
                    Action a = _actionsForUnblockingChildAdditions.Dequeue();
                    a?.Invoke();
                }
            }
        }

        private bool _alreadyDisabledFlowControlForPendingCmdletActionsQueue = false;

        internal void DisableFlowControlForPendingCmdletActionsQueue()
        {
            if (!_cmdletMode || _alreadyDisabledFlowControlForPendingCmdletActionsQueue)
            {
                return;
            }

            _alreadyDisabledFlowControlForPendingCmdletActionsQueue = true;

            long slotsToRelease = (long)(int.MaxValue / 2) - (long)(_jobResultsThrottlingSemaphore.CurrentCount);
            if ((slotsToRelease > 0) && (slotsToRelease < int.MaxValue))
            {
                _jobResultsThrottlingSemaphore.Release((int)slotsToRelease);
            }
        }

        /// <summary>
        /// Adds and starts a child job.
        /// </summary>
        /// <param name="childJob">Child job to add.</param>
        /// <param name="flags">Flags of the child job.</param>
        /// <param name="jobEnqueuedAction">Action to run after enqueuing the job.</param>
        /// <exception cref="ArgumentException">
        /// Thrown when the child job is not in the <see cref="JobState.NotStarted"/> state.
        /// (because this can lead to race conditions - the child job can finish before the parent job has a chance to register for child job events)
        /// </exception>
        internal void AddChildJobWithoutBlocking(StartableJob childJob, ChildJobFlags flags, Action jobEnqueuedAction = null)
        {
            ArgumentNullException.ThrowIfNull(childJob);
            if (childJob.JobStateInfo.State != JobState.NotStarted)
            {
                throw new ArgumentException(RemotingErrorIdStrings.ThrottlingJobChildAlreadyRunning, nameof(childJob));
            }
                
            this.AssertNotDisposed();

            JobStateInfo newJobStateInfo = null;
            lock (_lockObject)
            {
                if (this.IsEndOfChildJobs)
                {
                    throw new InvalidOperationException(RemotingErrorIdStrings.ThrottlingJobChildAddedAfterEndOfChildJobs);
                }

                if (_isStopping)
                {
                    return;
                }

                if (_countOfAllChildJobs == 0)
                {
                    newJobStateInfo = new JobStateInfo(JobState.Running);
                }

                if ((ChildJobFlags.CreatesChildJobs & flags) == ChildJobFlags.CreatesChildJobs)
                {
                    _setOfChildJobsThatCanAddMoreChildJobs.Add(childJob.InstanceId);
                }

                this.ChildJobs.Add(childJob);
                _childJobLocations.Add(childJob.Location);
                _countOfAllChildJobs++;

                this.WriteWarningAboutHighUsageOfFlowControlBuffers(this.CountOfRunningOrReadyToRunChildJobs);
                if (this.CountOfRunningOrReadyToRunChildJobs > _maxReadyToRunJobs)
                {
                    _actionsForUnblockingChildAdditions.Enqueue(jobEnqueuedAction);
                }
                else
                {
                    jobEnqueuedAction?.Invoke();
                }
            }

            if (newJobStateInfo != null)
            {
                this.SetJobState(newJobStateInfo.State, newJobStateInfo.Reason);
            }

            this.ChildJobAdded.SafeInvoke(this, new ThrottlingJobChildAddedEventArgs(childJob));

            childJob.SetParentActivityIdGetter(this.GetProgressActivityId);
            childJob.StateChanged += this.childJob_StateChanged;
            if (_cmdletMode)
            {
                childJob.Results.DataAdded += childJob_ResultsAdded;
            }

            this.EnqueueReadyToRunChildJob(childJob);

            this.ReportProgress(minimizeFrequentUpdates: true);
        }

        private void childJob_ResultsAdded(object sender, DataAddedEventArgs e)
        {
            Dbg.Assert(_jobResultsThrottlingSemaphore != null, "JobResultsThrottlingSemaphore should be non-null if childJob_ResultsAdded handled is registered");
            try
            {
                long jobResultsUpdatedCount = Interlocked.Increment(ref _jobResultsCurrentCount);
                this.WriteWarningAboutHighUsageOfFlowControlBuffers(jobResultsUpdatedCount);

                _jobResultsThrottlingSemaphore.Wait(_cancellationTokenSource.Token);
            }
            catch (ObjectDisposedException)
            {
            }
            catch (OperationCanceledException)
            {
            }
        }

        private readonly object _alreadyWroteFlowControlBuffersHighMemoryUsageWarningLock = new object();
        private bool _alreadyWroteFlowControlBuffersHighMemoryUsageWarning;

        private const long FlowControlBuffersHighMemoryUsageThreshold = 30000;

        private void WriteWarningAboutHighUsageOfFlowControlBuffers(long currentCount)
        {
            if (!_cmdletMode)
            {
                return;
            }

            if (currentCount < FlowControlBuffersHighMemoryUsageThreshold)
            {
                return;
            }

            lock (_alreadyWroteFlowControlBuffersHighMemoryUsageWarningLock)
            {
                if (_alreadyWroteFlowControlBuffersHighMemoryUsageWarning)
                {
                    return;
                }

                _alreadyWroteFlowControlBuffersHighMemoryUsageWarning = true;
            }

            string warningMessage = string.Format(
                CultureInfo.InvariantCulture,
                RemotingErrorIdStrings.ThrottlingJobFlowControlMemoryWarning,
                this.Command);
            this.WriteWarning(warningMessage);
        }

        internal event EventHandler<ThrottlingJobChildAddedEventArgs> ChildJobAdded;

        private int _maximumConcurrentChildJobs;
        private int _extraCapacityForRunningQueryJobs;
        private int _extraCapacityForRunningAllJobs;
        private bool _inBoostModeToPreventQueryJobDeadlock;
        private Queue<StartableJob> _readyToRunQueryJobs;
        private Queue<StartableJob> _readyToRunRegularJobs;
        private Queue<Action> _actionsForUnblockingChildAdditions;
        private int _maxReadyToRunJobs;
        private readonly SemaphoreSlim _jobResultsThrottlingSemaphore;
        private long _jobResultsCurrentCount;

        private static readonly int s_maximumReadyToRunJobs = 10000;

        private void SetupThrottlingQueue(int maximumConcurrentChildJobs)
        {
            _maximumConcurrentChildJobs = maximumConcurrentChildJobs > 0 ? maximumConcurrentChildJobs : int.MaxValue;
            if (_cmdletMode)
            {
                _maxReadyToRunJobs = s_maximumReadyToRunJobs;
            }
            else
            {
                _maxReadyToRunJobs = int.MaxValue;
            }

            _extraCapacityForRunningAllJobs = _maximumConcurrentChildJobs;
            _extraCapacityForRunningQueryJobs = Math.Max(1, _extraCapacityForRunningAllJobs / 2);

            _inBoostModeToPreventQueryJobDeadlock = false;
            _readyToRunQueryJobs = new Queue<StartableJob>();
            _readyToRunRegularJobs = new Queue<StartableJob>();
            _actionsForUnblockingChildAdditions = new Queue<Action>();
        }

        private void StartChildJobIfPossible()
        {
            StartableJob readyToRunChildJob = null;
            lock (_lockObject)
            {
                do
                {
                    if ((_readyToRunQueryJobs.Count > 0) &&
                        (_extraCapacityForRunningQueryJobs > 0) &&
                        (_extraCapacityForRunningAllJobs > 0))
                    {
                        _extraCapacityForRunningQueryJobs--;
                        _extraCapacityForRunningAllJobs--;
                        readyToRunChildJob = _readyToRunQueryJobs.Dequeue();
                        break;
                    }

                    if ((_readyToRunRegularJobs.Count > 0) &&
                        (_extraCapacityForRunningAllJobs > 0))
                    {
                        _extraCapacityForRunningAllJobs--;
                        readyToRunChildJob = _readyToRunRegularJobs.Dequeue();
                        break;
                    }
                } while (false);
            }

            readyToRunChildJob?.StartJob();
        }

        private void EnqueueReadyToRunChildJob(StartableJob childJob)
        {
            lock (_lockObject)
            {
                bool isQueryJob = _setOfChildJobsThatCanAddMoreChildJobs.Contains(childJob.InstanceId);
                if (isQueryJob &&
                    !_inBoostModeToPreventQueryJobDeadlock &&
                    (_maximumConcurrentChildJobs == 1))
                {
                    _inBoostModeToPreventQueryJobDeadlock = true;
                    _extraCapacityForRunningAllJobs++;
                }

                if (isQueryJob)
                {
                    _readyToRunQueryJobs.Enqueue(childJob);
                }
                else
                {
                    _readyToRunRegularJobs.Enqueue(childJob);
                }
            }

            StartChildJobIfPossible();
        }

        private void MakeRoomForRunningOtherJobs(Job completedChildJob)
        {
            lock (_lockObject)
            {
                _extraCapacityForRunningAllJobs++;

                bool isQueryJob = _setOfChildJobsThatCanAddMoreChildJobs.Contains(completedChildJob.InstanceId);
                if (isQueryJob)
                {
                    _setOfChildJobsThatCanAddMoreChildJobs.Remove(completedChildJob.InstanceId);

                    _extraCapacityForRunningQueryJobs++;
                    if (_inBoostModeToPreventQueryJobDeadlock && (_setOfChildJobsThatCanAddMoreChildJobs.Count == 0))
                    {
                        _inBoostModeToPreventQueryJobDeadlock = false;
                        _extraCapacityForRunningAllJobs--;
                    }
                }
            }

            StartChildJobIfPossible();
        }

        private void FigureOutIfThrottlingJobIsCompleted()
        {
            JobStateInfo finalJobStateInfo = null;
            lock (_lockObject)
            {
                if (this.IsThrottlingJobCompleted && !IsFinishedState(this.JobStateInfo.State))
                {
                    if (_isStopping)
                    {
                        finalJobStateInfo = new JobStateInfo(JobState.Stopped, null);
                    }
                    else if (_countOfFailedChildJobs > 0)
                    {
                        finalJobStateInfo = new JobStateInfo(JobState.Failed, null);
                    }
                    else if (_countOfStoppedChildJobs > 0)
                    {
                        finalJobStateInfo = new JobStateInfo(JobState.Stopped, null);
                    }
                    else
                    {
                        finalJobStateInfo = new JobStateInfo(JobState.Completed);
                    }
                }
            }

            if (finalJobStateInfo != null)
            {
                this.SetJobState(finalJobStateInfo.State, finalJobStateInfo.Reason);
                this.CloseAllStreams();
            }
        }

        /// <summary>
        /// Notifies this <see cref="ThrottlingJob"/> object that no more child jobs will be added.
        /// </summary>
        internal void EndOfChildJobs()
        {
            this.AssertNotDisposed();
            lock (_lockObject)
            {
                _ownerWontSubmitNewChildJobs = true;
            }

            this.FigureOutIfThrottlingJobIsCompleted();
        }

        /// <summary>
        /// Stop this job object and all the <see cref="System.Management.Automation.Job.ChildJobs"/>.
        /// </summary>
        public override void StopJob()
        {
            List<Job> childJobsToStop = null;
            lock (_lockObject)
            {
                if (!(_isStopping || this.IsThrottlingJobCompleted))
                {
                    _isStopping = true;
                    childJobsToStop = this.GetChildJobsSnapshot();
                }
            }

            if (childJobsToStop != null)
            {
                this.SetJobState(JobState.Stopping);

                _cancellationTokenSource.Cancel();
                foreach (Job childJob in childJobsToStop)
                {
                    if (!childJob.IsFinishedState(childJob.JobStateInfo.State))
                    {
                        childJob.StopJob();
                    }
                }

                this.FigureOutIfThrottlingJobIsCompleted();
            }

            this.Finished.WaitOne();
        }

        private bool _isStopping;
        private readonly CancellationTokenSource _cancellationTokenSource = new CancellationTokenSource();

        private void childJob_StateChanged(object sender, JobStateEventArgs e)
        {
            Dbg.Assert(sender != null, "Only our internal implementation of Job should raise this event and it should make sure that sender != null");
            Dbg.Assert(sender is Job, "Only our internal implementation of Job should raise this event and it should make sure that sender is Job");
            var childJob = (Job)sender;

            if ((e.PreviousJobStateInfo.State == JobState.Blocked) && (e.JobStateInfo.State != JobState.Blocked))
            {
                bool parentJobGotUnblocked = false;
                lock (_lockObject)
                {
                    _countOfBlockedChildJobs--;
                    if (_countOfBlockedChildJobs == 0)
                    {
                        parentJobGotUnblocked = true;
                    }
                }

                if (parentJobGotUnblocked)
                {
                    this.SetJobState(JobState.Running);
                }
            }

            switch (e.JobStateInfo.State)
            {
                // intermediate states
                case JobState.Blocked:
                    lock (_lockObject)
                    {
                        _countOfBlockedChildJobs++;
                    }

                    this.SetJobState(JobState.Blocked);
                    break;

                // 3 finished states
                case JobState.Failed:
                case JobState.Stopped:
                case JobState.Completed:
                    childJob.StateChanged -= childJob_StateChanged;
                    this.MakeRoomForRunningOtherJobs(childJob);
                    lock (_lockObject)
                    {
                        if (e.JobStateInfo.State == JobState.Failed)
                        {
                            _countOfFailedChildJobs++;
                        }
                        else if (e.JobStateInfo.State == JobState.Stopped)
                        {
                            _countOfStoppedChildJobs++;
                        }
                        else if (e.JobStateInfo.State == JobState.Completed)
                        {
                            _countOfSuccessfullyCompletedChildJobs++;
                        }

                        if (_actionsForUnblockingChildAdditions.Count > 0)
                        {
                            Action a = _actionsForUnblockingChildAdditions.Dequeue();
                            a?.Invoke();
                        }

                        if (_cmdletMode)
                        {
                            foreach (PSStreamObject streamObject in childJob.Results.ReadAll())
                            {
                                this.Results.Add(streamObject);
                            }

                            this.ChildJobs.Remove(childJob);
                            _setOfChildJobsThatCanAddMoreChildJobs.Remove(childJob.InstanceId);
                            childJob.Dispose();
                        }
                    }

                    this.ReportProgress(minimizeFrequentUpdates: !this.IsThrottlingJobCompleted);
                    break;

                default:
                    // do nothing
                    break;
            }

            this.FigureOutIfThrottlingJobIsCompleted();
        }

        private List<Job> GetChildJobsSnapshot()
        {
            lock (_lockObject)
            {
                return new List<Job>(this.ChildJobs);
            }
        }

        /// <summary>
        /// Indicates if job has more data available.
        /// <see langword="true"/> if any of the child jobs have more data OR if <see cref="EndOfChildJobs"/> have not been called yet;
        /// <see langword="false"/> otherwise.
        /// </summary>
        public override bool HasMoreData
        {
            get
            {
                return this.GetChildJobsSnapshot().Any(static childJob => childJob.HasMoreData) || (this.Results.Count != 0);
            }
        }

        /// <summary>
        /// Comma-separated list of locations of <see cref="System.Management.Automation.Job.ChildJobs"/>.
        /// </summary>
        public override string Location
        {
            get
            {
                lock (_lockObject)
                {
                    return string.Join(", ", _childJobLocations);
                }
            }
        }

        private readonly HashSet<string> _childJobLocations = new HashSet<string>(StringComparer.OrdinalIgnoreCase);

        /// <summary>
        /// Status message associated with the Job.
        /// </summary>
        public override string StatusMessage
        {
            get
            {
                int completedChildJobs;
                int totalChildJobs;
                lock (_lockObject)
                {
                    completedChildJobs = this.CountOfFinishedChildJobs;
                    totalChildJobs = _countOfAllChildJobs;
                }

                string totalChildJobsString = totalChildJobs.ToString(CultureInfo.CurrentCulture);
                if (!this.IsEndOfChildJobs)
                {
                    totalChildJobsString += "+";
                }

                return string.Format(
                    CultureInfo.CurrentUICulture,
                    RemotingErrorIdStrings.ThrottlingJobStatusMessage,
                    completedChildJobs,
                    totalChildJobsString);
            }
        }

        #region Forwarding results to a cmdlet

        internal override void ForwardAvailableResultsToCmdlet(Cmdlet cmdlet)
        {
            this.AssertNotDisposed();

            base.ForwardAvailableResultsToCmdlet(cmdlet);
            foreach (Job childJob in this.GetChildJobsSnapshot())
            {
                childJob.ForwardAvailableResultsToCmdlet(cmdlet);
            }
        }

        private sealed class ForwardingHelper : IDisposable
        {
            // This is higher than 1000 used in
            //      RxExtensionMethods+ToEnumerableObserver<T>.BlockingCollectionCapacity
            // and in
            //      RemoteDiscoveryHelper.BlockingCollectionCapacity
            // It needs to be higher, because the high value is used as an attempt to workaround the fact that
            // WSMan will timeout if an OnNext call blocks for more than X minutes.

            // This is a static field (instead of a constant) to make it possible to set through tests (and/or by customers if needed for a workaround)
            internal static readonly int AggregationQueueMaxCapacity = 10000;

            private readonly ThrottlingJob _throttlingJob;

            private readonly object _myLock;
            private readonly BlockingCollection<PSStreamObject> _aggregatedResults;
            private readonly HashSet<Job> _monitoredJobs;

            private readonly CancellationTokenSource _cancellationTokenSource = new CancellationTokenSource();
            private bool _disposed;

            private ForwardingHelper(ThrottlingJob throttlingJob)
            {
                _throttlingJob = throttlingJob;

                _myLock = new object();
                _monitoredJobs = new HashSet<Job>();

                _aggregatedResults = new BlockingCollection<PSStreamObject>();
            }

            private void StartMonitoringJob(Job job)
            {
                lock (_myLock)
                {
                    if (_disposed || _stoppedMonitoringAllJobs)
                    {
                        return;
                    }

                    if (_monitoredJobs.Contains(job))
                    {
                        return;
                    }

                    _monitoredJobs.Add(job);

                    job.Results.DataAdded += this.MonitoredJobResults_DataAdded;
                    job.StateChanged += MonitoredJob_StateChanged;
                }

                this.AggregateJobResults(job.Results);
                this.CheckIfMonitoredJobIsComplete(job);
            }

            private void StopMonitoringJob(Job job)
            {
                lock (_myLock)
                {
                    if (_monitoredJobs.Contains(job))
                    {
                        job.Results.DataAdded -= this.MonitoredJobResults_DataAdded;
                        job.StateChanged -= this.MonitoredJob_StateChanged;
                        _monitoredJobs.Remove(job);
                    }
                }
            }

            private void AggregateJobResults(PSDataCollection<PSStreamObject> resultsCollection)
            {
                lock (_myLock)
                {
                    // try not to remove results from a job, unless it seems safe ...
                    if (_disposed || _stoppedMonitoringAllJobs || _aggregatedResults.IsAddingCompleted || _cancellationTokenSource.IsCancellationRequested)
                    {
                        return;
                    }
                }

                // ... and after removing the results via ReadAll, we have to make sure that we don't drop them ...
                foreach (var result in resultsCollection.ReadAll())
                {
                    bool successfullyAggregatedResult = false;
                    try
                    {
                        lock (_myLock)
                        {
                            // try not to remove results from a job, unless it seems safe ...
                            if (!(_disposed || _stoppedMonitoringAllJobs || _aggregatedResults.IsAddingCompleted || _cancellationTokenSource.IsCancellationRequested))
                            {
                                _aggregatedResults.Add(result, _cancellationTokenSource.Token);
                                successfullyAggregatedResult = true;
                            }
                        }
                    }
                    catch (Exception) // BlockingCollection.Add can throw undocumented exceptions - we cannot just catch InvalidOperationException
                    {
                    }

                    // ... so if _aggregatedResults is not accepting new results, we will store them in the throttling job
                    if (!successfullyAggregatedResult)
                    {
                        this.StopMonitoringJob(_throttlingJob);
                        try
                        {
                            _throttlingJob.Results.Add(result);
                        }
                        catch (InvalidOperationException)
                        {
                            Dbg.Assert(false, "ThrottlingJob.Results was already closed when trying to preserve results aggregated by ForwardingHelper");
                        }
                    }
                }
            }

            private void CancelForwarding()
            {
                _cancellationTokenSource.Cancel();
                lock (_myLock)
                {
                    Dbg.Assert(!_disposed, "CancelForwarding should be unregistered before ForwardingHelper gets disposed");
                    _aggregatedResults.CompleteAdding();
                }
            }

            private void CheckIfMonitoredJobIsComplete(Job job)
            {
                CheckIfMonitoredJobIsComplete(job, job.JobStateInfo.State);
            }

            private void CheckIfMonitoredJobIsComplete(Job job, JobState jobState)
            {
                if (job.IsFinishedState(jobState))
                {
                    lock (_myLock)
                    {
                        this.StopMonitoringJob(job);
                    }
                }
            }

            private void CheckIfThrottlingJobIsComplete()
            {
                if (_throttlingJob.IsThrottlingJobCompleted)
                {
                    List<PSDataCollection<PSStreamObject>> resultsToAggregate = new List<PSDataCollection<PSStreamObject>>();
                    lock (_myLock)
                    {
                        foreach (Job registeredJob in _monitoredJobs)
                        {
                            resultsToAggregate.Add(registeredJob.Results);
                        }

                        foreach (Job throttledJob in _throttlingJob.GetChildJobsSnapshot())
                        {
                            resultsToAggregate.Add(throttledJob.Results);
                        }

                        resultsToAggregate.Add(_throttlingJob.Results);
                    }

                    foreach (PSDataCollection<PSStreamObject> resultToAggregate in resultsToAggregate)
                    {
                        this.AggregateJobResults(resultToAggregate);
                    }

                    lock (_myLock)
                    {
                        if (!_disposed && !_aggregatedResults.IsAddingCompleted)
                        {
                            _aggregatedResults.CompleteAdding();
                        }
                    }
                }
            }

            private void MonitoredJobResults_DataAdded(object sender, DataAddedEventArgs e)
            {
                var resultsCollection = (PSDataCollection<PSStreamObject>)sender;
                this.AggregateJobResults(resultsCollection);
            }

            private void MonitoredJob_StateChanged(object sender, JobStateEventArgs e)
            {
                var job = (Job)sender;
                this.CheckIfMonitoredJobIsComplete(job, e.JobStateInfo.State);
            }

            private void ThrottlingJob_ChildJobAdded(object sender, ThrottlingJobChildAddedEventArgs e)
            {
                this.StartMonitoringJob(e.AddedChildJob);
            }

            private void ThrottlingJob_StateChanged(object sender, JobStateEventArgs e)
            {
                this.CheckIfThrottlingJobIsComplete();
            }

            private void AttemptToPreserveAggregatedResults()
            {
#if DEBUG
                lock (_myLock)
                {
                    Dbg.Assert(!_disposed, "AttemptToPreserveAggregatedResults should be called before disposing ForwardingHelper");
                    Dbg.Assert(_stoppedMonitoringAllJobs, "Caller should guarantee no-more-results before calling AttemptToPreserveAggregatedResults (1)");
                    Dbg.Assert(_aggregatedResults.IsAddingCompleted, "Caller should guarantee no-more-results before calling AttemptToPreserveAggregatedResults (2)");
                }
#endif

                bool isThrottlingJobFinished = false;
                foreach (var aggregatedButNotYetProcessedResult in _aggregatedResults)
                {
                    if (!isThrottlingJobFinished)
                    {
                        try
                        {
                            _throttlingJob.Results.Add(aggregatedButNotYetProcessedResult);
                        }
                        catch (PSInvalidOperationException)
                        {
                            isThrottlingJobFinished = _throttlingJob.IsFinishedState(_throttlingJob.JobStateInfo.State);
                            Dbg.Assert(isThrottlingJobFinished, "Buffers should not be closed before throttling job is stopped");
                        }
                    }
                }
            }

#if DEBUG
            // CDXML_CLIXML_TEST testability hook

            private static readonly bool s_isCliXmlTestabilityHookActive = GetIsCliXmlTestabilityHookActive();

            private static bool GetIsCliXmlTestabilityHookActive()
            {
                return !string.IsNullOrEmpty(Environment.GetEnvironmentVariable("CDXML_CLIXML_TEST"));
            }

            internal static void ProcessCliXmlTestabilityHook(PSStreamObject streamObject)
            {
                if (!s_isCliXmlTestabilityHookActive)
                {
                    return;
                }

                if (streamObject.ObjectType != PSStreamObjectType.Output)
                {
                    return;
                }

                if (streamObject.Value == null)
                {
                    return;
                }

                if (!(PSObject.AsPSObject(streamObject.Value).BaseObject.GetType().Name.Equals("CimInstance")))
                {
                    return;
                }

                string serializedForm = PSSerializer.Serialize(streamObject.Value, depth: 1);
                object deserializedObject = PSSerializer.Deserialize(serializedForm);
                streamObject.Value = PSObject.AsPSObject(deserializedObject).BaseObject;
            }
#endif

            private void ForwardResults(Cmdlet cmdlet)
            {
                try
                {
                    foreach (var result in _aggregatedResults.GetConsumingEnumerable(_throttlingJob._cancellationTokenSource.Token))
                    {
                        if (result != null)
                        {
#if DEBUG
                            // CDXML_CLIXML_TEST testability hook
                            ProcessCliXmlTestabilityHook(result);
#endif
                            try
                            {
                                result.WriteStreamObject(cmdlet);
                            }
                            finally
                            {
                                if (_throttlingJob._cmdletMode)
                                {
                                    Dbg.Assert(_throttlingJob._jobResultsThrottlingSemaphore != null, "JobResultsThrottlingSemaphore should be present in cmdlet mode");
                                    Interlocked.Decrement(ref _throttlingJob._jobResultsCurrentCount);
                                    _throttlingJob._jobResultsThrottlingSemaphore.Release();
                                }
                            }
                        }
                    }
                }
                catch
                {
                    this.StopMonitoringAllJobs();
                    this.AttemptToPreserveAggregatedResults();

                    throw;
                }
            }

            private bool _stoppedMonitoringAllJobs;

            private void StopMonitoringAllJobs()
            {
                _cancellationTokenSource.Cancel();
                lock (_myLock)
                {
                    _stoppedMonitoringAllJobs = true;

                    List<Job> snapshotOfCurrentlyMonitoredJobs = _monitoredJobs.ToList();
                    foreach (Job monitoredJob in snapshotOfCurrentlyMonitoredJobs)
                    {
                        this.StopMonitoringJob(monitoredJob);
                    }

                    Dbg.Assert(_monitoredJobs.Count == 0, "No monitored jobs should be left after ForwardingHelper is disposed");

                    if (!_disposed && !_aggregatedResults.IsAddingCompleted)
                    {
                        _aggregatedResults.CompleteAdding();
                    }
                }
            }

            public void Dispose()
            {
                GC.SuppressFinalize(this);
                _cancellationTokenSource.Cancel();
                lock (_myLock)
                {
                    if (_disposed)
                    {
                        return;
                    }

                    this.StopMonitoringAllJobs();
                    _aggregatedResults.Dispose();
                    _cancellationTokenSource.Dispose();
                    _disposed = true;
                }
            }

            public static void ForwardAllResultsToCmdlet(ThrottlingJob throttlingJob, Cmdlet cmdlet, CancellationToken? cancellationToken)
            {
                using (var helper = new ForwardingHelper(throttlingJob))
                {
                    try
                    {
                        throttlingJob.ChildJobAdded += helper.ThrottlingJob_ChildJobAdded;

                        try
                        {
                            throttlingJob.StateChanged += helper.ThrottlingJob_StateChanged;

                            IDisposable cancellationTokenRegistration = null;
                            if (cancellationToken.HasValue)
                            {
                                cancellationTokenRegistration = cancellationToken.Value.Register(helper.CancelForwarding);
                            }

                            try
                            {
                                Interlocked.MemoryBarrier();
                                ThreadPool.QueueUserWorkItem(
                                        delegate
                                        {
                                            helper.StartMonitoringJob(throttlingJob);
                                            foreach (Job childJob in throttlingJob.GetChildJobsSnapshot())
                                            {
                                                helper.StartMonitoringJob(childJob);
                                            }

                                            helper.CheckIfThrottlingJobIsComplete();
                                        });

                                helper.ForwardResults(cmdlet);
                            }
                            finally
                            {
                                cancellationTokenRegistration?.Dispose();
                            }
                        }
                        finally
                        {
                            throttlingJob.StateChanged -= helper.ThrottlingJob_StateChanged;
                        }
                    }
                    finally
                    {
                        throttlingJob.ChildJobAdded -= helper.ThrottlingJob_ChildJobAdded;
                    }
                }
            }
        }

        internal override void ForwardAllResultsToCmdlet(Cmdlet cmdlet)
        {
            this.ForwardAllResultsToCmdlet(cmdlet, cancellationToken: null);
        }

        private void ForwardAllResultsToCmdlet(Cmdlet cmdlet, CancellationToken? cancellationToken)
        {
            this.AssertNotDisposed();
            ForwardingHelper.ForwardAllResultsToCmdlet(this, cmdlet, cancellationToken);
        }

        #endregion Forwarding results to a cmdlet
    }

    internal class ThrottlingJobChildAddedEventArgs : EventArgs
    {
        internal Job AddedChildJob { get; }

        internal ThrottlingJobChildAddedEventArgs(Job addedChildJob)
        {
            Dbg.Assert(addedChildJob != null, "Caller should verify addedChildJob != null");
            AddedChildJob = addedChildJob;
        }
    }
}