/// <summary>
        /// Performs initialization of cmdlet execution.
        /// </summary>
        public override void BeginProcessing()
        {
            if (this.AsJob.IsPresent)
            {
                MshCommandRuntime commandRuntime       = (MshCommandRuntime)this.Cmdlet.CommandRuntime; // PSCmdlet.CommandRuntime is always MshCommandRuntime
                string            conflictingParameter = null;
                if (commandRuntime.WhatIf.IsPresent)
                {
                    conflictingParameter = "WhatIf";
                }
                else if (commandRuntime.Confirm.IsPresent)
                {
                    conflictingParameter = "Confirm";
                }

                if (conflictingParameter != null)
                {
                    string errorMessage = string.Format(
                        CultureInfo.InvariantCulture,
                        CmdletizationResources.SessionBasedWrapper_ShouldProcessVsJobConflict,
                        conflictingParameter);
                    throw new InvalidOperationException(errorMessage);
                }
            }

            _parentJob = new ThrottlingJob(
                command: Job.GetCommandTextFromInvocationInfo(this.Cmdlet.MyInvocation),
                jobName: this.GenerateParentJobName(),
                jobTypeName: CIMJobType,
                maximumConcurrentChildJobs: this.ThrottleLimit,
                cmdletMode: !this.AsJob.IsPresent);
        }
        public override void ProcessRecord(QueryBuilder query, MethodInvocationInfo methodInvocationInfo, bool passThru)
        {
            Action <TSession, TObjectInstance> actionAgainstResults = null;

            this.parentJob.DisableFlowControlForPendingJobsQueue();
            ThrottlingJob   closureOverParentJob = this.parentJob;
            SwitchParameter closureOverAsJob     = this.AsJob;

            foreach (TSession local in this.GetSessionsToActAgainst(query))
            {
                if (actionAgainstResults == null)
                {
                    actionAgainstResults = delegate(TSession sessionForMethodInvocationJob, TObjectInstance objectInstance)
                    {
                        StartableJob childJob = ((SessionBasedCmdletAdapter <TObjectInstance, TSession>) this).DoCreateInstanceMethodInvocationJob(sessionForMethodInvocationJob, objectInstance, methodInvocationInfo, passThru, closureOverAsJob.IsPresent);
                        if (childJob != null)
                        {
                            closureOverParentJob.AddChildJobAndPotentiallyBlock(childJob, ThrottlingJob.ChildJobFlags.None);
                        }
                    };
                }
                StartableJob job = this.DoCreateQueryJob(local, query, actionAgainstResults);
                if (job != null)
                {
                    if (!this.AsJob.IsPresent)
                    {
                        this.parentJob.AddChildJobAndPotentiallyBlock(base.Cmdlet, job, ThrottlingJob.ChildJobFlags.CreatesChildJobs);
                    }
                    else
                    {
                        this.parentJob.AddChildJobWithoutBlocking(job, ThrottlingJob.ChildJobFlags.CreatesChildJobs, null);
                    }
                }
            }
        }
            private ForwardingHelper(ThrottlingJob throttlingJob)
            {
                _throttlingJob = throttlingJob;

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

                _aggregatedResults = new BlockingCollection <PSStreamObject>();
            }
            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
                            {
                                if (cancellationTokenRegistration != null)
                                {
                                    cancellationTokenRegistration.Dispose();
                                }
                            }
                        }
                        finally
                        {
                            throttlingJob.StateChanged -= helper.ThrottlingJob_StateChanged;
                        }
                    }
                    finally
                    {
                        throttlingJob.ChildJobAdded -= helper.ThrottlingJob_ChildJobAdded;
                    }
                }
            }
 protected virtual void Dispose(bool disposing)
 {
     if (!this.disposed)
     {
         if (disposing && (this.parentJob != null))
         {
             this.parentJob.Dispose();
             this.parentJob = null;
         }
         this.disposed = true;
     }
 }
 /// <summary>
 /// Performs cleanup after cmdlet execution.
 /// </summary>
 public override void EndProcessing()
 {
     _parentJob.EndOfChildJobs();
     if (this.AsJob.IsPresent)
     {
         this.Cmdlet.WriteObject(_parentJob);
         this.Cmdlet.JobRepository.Add(_parentJob);
         _parentJob = null; // this class doesn't own parentJob after it has been emitted to the outside world
     }
     else
     {
         _parentJob.ForwardAllResultsToCmdlet(this.Cmdlet);
         _parentJob.Finished.WaitOne();
     }
 }
 public override void EndProcessing()
 {
     this.parentJob.EndOfChildJobs();
     if (this.AsJob.IsPresent)
     {
         base.Cmdlet.WriteObject(this.parentJob);
         base.Cmdlet.JobRepository.Add(this.parentJob);
         this.parentJob = null;
     }
     else
     {
         this.parentJob.ForwardAllResultsToCmdlet(base.Cmdlet);
         this.parentJob.Finished.WaitOne();
     }
 }
 public override void BeginProcessing()
 {
     if (this.AsJob.IsPresent)
     {
         MshCommandRuntime commandRuntime = (MshCommandRuntime)base.Cmdlet.CommandRuntime;
         string            str            = null;
         if (commandRuntime.WhatIf.IsPresent)
         {
             str = "WhatIf";
         }
         else if (commandRuntime.Confirm.IsPresent)
         {
             str = "Confirm";
         }
         if (str != null)
         {
             throw new InvalidOperationException(string.Format(CultureInfo.InvariantCulture, CmdletizationResources.SessionBasedWrapper_ShouldProcessVsJobConflict, new object[] { str }));
         }
     }
     this.parentJob = new ThrottlingJob(Job.GetCommandTextFromInvocationInfo(base.Cmdlet.MyInvocation), this.GenerateParentJobName(), "CimJob", this.ThrottleLimit, !this.AsJob.IsPresent);
 }
        /// <summary>
        /// Queries for instance and invokes an instance method.
        /// </summary>
        /// <param name="query">Query parameters.</param>
        /// <param name="methodInvocationInfo">Method invocation details.</param>
        /// <param name="passThru"><c>true</c> if successful method invocations should emit downstream the object instance being operated on.</param>
        public override void ProcessRecord(QueryBuilder query, MethodInvocationInfo methodInvocationInfo, bool passThru)
        {
            _parentJob.DisableFlowControlForPendingJobsQueue();

            ThrottlingJob   closureOverParentJob = _parentJob;
            SwitchParameter closureOverAsJob     = this.AsJob;

            foreach (TSession sessionForJob in this.GetSessionsToActAgainst(query))
            {
                StartableJob queryJob = this.DoCreateQueryJob(
                    sessionForJob,
                    query,
                    delegate(TSession sessionForMethodInvocationJob, TObjectInstance objectInstance)
                {
                    StartableJob methodInvocationJob = this.DoCreateInstanceMethodInvocationJob(
                        sessionForMethodInvocationJob,
                        objectInstance,
                        methodInvocationInfo,
                        passThru,
                        closureOverAsJob.IsPresent);

                    if (methodInvocationJob != null)
                    {
                        closureOverParentJob.AddChildJobAndPotentiallyBlock(methodInvocationJob, ThrottlingJob.ChildJobFlags.None);
                    }
                });

                if (queryJob != null)
                {
                    if (!this.AsJob.IsPresent)
                    {
                        _parentJob.AddChildJobAndPotentiallyBlock(this.Cmdlet, queryJob, ThrottlingJob.ChildJobFlags.CreatesChildJobs);
                    }
                    else
                    {
                        _parentJob.AddChildJobWithoutBlocking(queryJob, ThrottlingJob.ChildJobFlags.CreatesChildJobs);
                    }
                }
            }
        }