private Runspace AssignRunspaceIfPossible()
        {
            Runspace value = null;

            lock (this._runspaceCache.TimerServicingSyncObject)
            {
                IEnumerable <Item <Runspace> > items      = this._runspaceCache.Cast <Item <Runspace> >();
                IEnumerator <Item <Runspace> > enumerator = items.Where <Item <Runspace> >((Item <Runspace> item) => !item.Busy).GetEnumerator();
                using (enumerator)
                {
                    if (enumerator.MoveNext())
                    {
                        Item <Runspace> current = enumerator.Current;
                        current.Idle = false;
                        current.Busy = true;
                        value        = current.Value;
                    }
                }
                if ((value == null || value.RunspaceStateInfo.State != RunspaceState.Opened) && (this._maxRunspaces == -1 || this._runspaceCache.Cache.Count < this._maxRunspaces))
                {
                    value = LocalRunspaceProvider.CreateLocalActivityRunspace(this._languageMode, true);
                    value.Open();
                    this._tracer.WriteMessage("New local runspace created");
                    this._runspaceCache.Add(new Item <Runspace>(value, value.InstanceId));
                }
            }
            return(value);
        }
        internal static Runspace CreateLocalActivityRunspace(PSLanguageMode?languageMode = null, bool useCurrentThreadForExecution = true)
        {
            InitialSessionState initialSessionStateWithSharedTypesAndNoFormat = LocalRunspaceProvider.GetInitialSessionStateWithSharedTypesAndNoFormat();

            if (SystemPolicy.GetSystemLockdownPolicy() == SystemEnforcementMode.Enforce)
            {
                initialSessionStateWithSharedTypesAndNoFormat.LanguageMode = PSLanguageMode.ConstrainedLanguage;
            }
            if (languageMode.HasValue && languageMode.HasValue)
            {
                initialSessionStateWithSharedTypesAndNoFormat.LanguageMode = languageMode.Value;
            }
            SessionStateVariableEntry sessionStateVariableEntry = new SessionStateVariableEntry("RunningInPSWorkflowEndpoint", (object)((bool)1), "True if we're in a Workflow Endpoint", ScopedItemOptions.Constant);

            initialSessionStateWithSharedTypesAndNoFormat.Variables.Add(sessionStateVariableEntry);
            Runspace runspace = RunspaceFactory.CreateRunspace(initialSessionStateWithSharedTypesAndNoFormat);

            if (useCurrentThreadForExecution)
            {
                runspace.ThreadOptions = PSThreadOptions.UseCurrentThread;
            }
            return(runspace);
        }