public SingleThreadedRelayAddressedMultiQueueWorkerExceptionless(
            string name,
            Action <TItem, IItemsReleaser <TKey> > relayUserAction,
            ThreadPriority threadPriority, bool markThreadAsBackground, ApartmentState?apartmentState, ILogger debugLogger,
            int maxPriority, uint maxParallelUsingItemsCount, uint maxTotalOnetimeItemsUsages)
        {
            _syncRunFlags    = new object();
            _syncUserActions = new object();

            _name            = name;
            _relayUserAction = relayUserAction ?? throw new ArgumentNullException(nameof(relayUserAction));
            _debugLogger     = debugLogger ?? throw new ArgumentNullException(nameof(debugLogger));

            _threadNotifyAboutQueueItemsCountChanged = new AutoResetEvent(false);
            _items = new ConcurrentQueueWithPriorityAndAddressUsageControlGuided <TKey, TItem>(maxPriority, maxParallelUsingItemsCount, maxTotalOnetimeItemsUsages);

            _isRunning     = true;
            _mustBeStopped = false;

            _workThread = new Thread(WorkingThreadStart)
            {
                Priority = threadPriority, IsBackground = markThreadAsBackground, Name = name
            };
            if (apartmentState.HasValue)
            {
                _workThread.SetApartmentState(apartmentState.Value);
            }
            _workThread.Start();
        }
        private void Update(string optionName, string optionValue)
        {
            switch (optionName.ToLower(CultureInfo.InvariantCulture))
            {
            case "applicationbase":
                this.AssertValueNotAssigned("applicationbase", this.ApplicationBase);
                this.ApplicationBase = Environment.ExpandEnvironmentVariables(optionValue);
                return;

            case "assemblyname":
                this.AssertValueNotAssigned("assemblyname", this.AssemblyName);
                this.AssemblyName = optionValue;
                return;

            case "pssessionconfigurationtypename":
                this.AssertValueNotAssigned("pssessionconfigurationtypename", this.EndPointConfigurationTypeName);
                this.EndPointConfigurationTypeName = optionValue;
                return;

            case "startupscript":
                this.AssertValueNotAssigned("startupscript", this.StartupScript);
                if (!optionValue.EndsWith(".ps1", StringComparison.OrdinalIgnoreCase))
                {
                    throw PSTraceSource.NewArgumentException("startupscript", "remotingerroridstrings", "StartupScriptNotCorrect", new object[] { "startupscript" });
                }
                this.StartupScript = Environment.ExpandEnvironmentVariables(optionValue);
                return;

            case "psmaximumreceivedobjectsizemb":
                this.AssertValueNotAssigned("psmaximumreceivedobjectsizemb", this.MaxReceivedObjectSizeMB);
                this.MaxReceivedObjectSizeMB = GetIntValueInBytes(optionValue);
                return;

            case "psmaximumreceiveddatasizepercommandmb":
                this.AssertValueNotAssigned("psmaximumreceiveddatasizepercommandmb", this.MaxReceivedCommandSizeMB);
                this.MaxReceivedCommandSizeMB = GetIntValueInBytes(optionValue);
                return;

            case "pssessionthreadoptions":
                this.AssertValueNotAssigned("pssessionthreadoptions", this.ShellThreadOptions);
                this.ShellThreadOptions = new PSThreadOptions?((PSThreadOptions)LanguagePrimitives.ConvertTo(optionValue, typeof(PSThreadOptions), CultureInfo.InvariantCulture));
                return;

            case "pssessionthreadapartmentstate":
                this.AssertValueNotAssigned("pssessionthreadapartmentstate", this.ShellThreadApartmentState);
                this.ShellThreadApartmentState = new ApartmentState?((ApartmentState)LanguagePrimitives.ConvertTo(optionValue, typeof(ApartmentState), CultureInfo.InvariantCulture));
                return;

            case "sessionconfigurationdata":
                this.AssertValueNotAssigned("sessionconfigurationdata", this.SessionConfigurationData);
                this.SessionConfigurationData = PSSessionConfigurationData.Create(optionValue);
                return;

            case "configfilepath":
                this.AssertValueNotAssigned("configfilepath", this.ConfigFilePath);
                this.ConfigFilePath = optionValue.ToString();
                return;
            }
        }
Esempio n. 3
0
        public static Thread RunInThread(this Action func, ApartmentState?model = null, bool isBackground = true)
        {
            Thread thread = new Thread(new ThreadStart(func));

            if (model.HasValue)
            {
                thread.SetApartmentState(model.Value);
            }
            thread.IsBackground = isBackground;
            thread.Start();
            return(thread);
        }
Esempio n. 4
0
        public async Task TaskIsCorrectlyScheduledOnStaThread()
        {
            // arrange
            ApartmentState?receivedState = null;
            var            act           = new Action(() => { receivedState = Thread.CurrentThread.GetApartmentState(); });

            // act
            await StaTask.Run(act);

            // assert
            receivedState.Should().NotBeNull();
            receivedState.Should().Be(ApartmentState.STA);
        }
Esempio n. 5
0
 private TaskQueue(string name, ApartmentState?apartmentState, ILogger logger, IThreadChanger threadChanger)
 {
     Logger        = logger;
     ThreadChanger = threadChanger;
     _worker       = new Thread(Work)
     {
         IsBackground = true,
         Name         = _threadName + name
     };
     if (apartmentState.HasValue)
     {
         _worker.SetApartmentState(apartmentState.Value);
     }
     _worker.Start();
 }
        public SingleThreadPriorityAddressedAsyncStarterExceptionless(
            string name,
            ThreadPriority threadPriority, bool markThreadAsBackground, ApartmentState?apartmentState, ILogger debugLogger,
            uint maxTotalFlow, uint maxFlowPerAddress, int priorityGradation, bool isWaitAllTasksCompleteNeededOnStop)
        {
            _name        = name;
            _debugLogger = debugLogger ?? throw new ArgumentNullException(nameof(debugLogger));
            _isWaitAllTasksCompleteNeededOnStop = isWaitAllTasksCompleteNeededOnStop;

            _totalFlowCounter       = new WaitableCounter(0);
            _asyncActionQueueWorker = new SingleThreadedRelayAddressedMultiQueueWorkerExceptionless <TAddressKey, Action <IItemsReleaser <TAddressKey> > >
                                      (
                _name, RunActionWithAsyncTailBack, threadPriority, markThreadAsBackground, apartmentState, debugLogger,
                priorityGradation,
                maxFlowPerAddress,
                maxTotalFlow);
        }
        public void RunningTaskSynchronouslyWillCorrectlySwitchToStaThread()
        {
            // arrange
            ApartmentState?receivedState = null;
            var            sut           = new StaTaskScheduler(1);
            var            act1          = new Action(() => { receivedState = Thread.CurrentThread.GetApartmentState(); });
            var            task          = new Task(act1);

            Thread.CurrentThread.GetApartmentState().Should().Be(ApartmentState.MTA);

            // act
            task.RunSynchronously(sut);

            // assert
            receivedState.Should().NotBeNull();
            receivedState.Should().Be(ApartmentState.STA);
        }
        public async Task ThreadIsCorrectlySetAsSta()
        {
            // arrange
            var            sut           = new StaTaskScheduler();
            ApartmentState?receivedState = null;
            var            act           = new Action(() =>
            {
                receivedState = Thread.CurrentThread.GetApartmentState();
            });

            // act
            await Task.Factory.StartNew(act, CancellationToken.None, TaskCreationOptions.None, sut);

            // assert
            receivedState.Should().NotBeNull();
            receivedState.Should().Be(ApartmentState.STA);
        }
        private void Update(string optionName, string optionValue)
        {
            switch (optionName.ToLower(CultureInfo.InvariantCulture))
            {
            case "applicationbase":
                this.AssertValueNotAssigned("applicationbase", (object)this.ApplicationBase);
                this.ApplicationBase = Environment.ExpandEnvironmentVariables(optionValue);
                break;

            case "assemblyname":
                this.AssertValueNotAssigned("assemblyname", (object)this.AssemblyName);
                this.AssemblyName = optionValue;
                break;

            case "pssessionconfigurationtypename":
                this.AssertValueNotAssigned("pssessionconfigurationtypename", (object)this.EndPointConfigurationTypeName);
                this.EndPointConfigurationTypeName = optionValue;
                break;

            case "startupscript":
                this.AssertValueNotAssigned("startupscript", (object)this.StartupScript);
                this.StartupScript = optionValue.EndsWith(".ps1", StringComparison.OrdinalIgnoreCase) ? Environment.ExpandEnvironmentVariables(optionValue) : throw ConfigurationDataFromXML.tracer.NewArgumentException("startupscript", "remotingerroridstrings", "StartupScriptNotCorrect", (object)"startupscript");
                break;

            case "psmaximumreceivedobjectsizemb":
                this.AssertValueNotAssigned("psmaximumreceivedobjectsizemb", (object)this.MaxReceivedObjectSizeMB);
                this.MaxReceivedObjectSizeMB = ConfigurationDataFromXML.GetIntValueInBytes(optionValue);
                break;

            case "psmaximumreceiveddatasizepercommandmb":
                this.AssertValueNotAssigned("psmaximumreceiveddatasizepercommandmb", (object)this.MaxReceivedCommandSizeMB);
                this.MaxReceivedCommandSizeMB = ConfigurationDataFromXML.GetIntValueInBytes(optionValue);
                break;

            case "pssessionthreadoptions":
                this.AssertValueNotAssigned("pssessionthreadoptions", (object)this.ShellThreadOptions);
                this.ShellThreadOptions = new PSThreadOptions?((PSThreadOptions)LanguagePrimitives.ConvertTo((object)optionValue, typeof(PSThreadOptions), (IFormatProvider)CultureInfo.InvariantCulture));
                break;

            case "pssessionthreadapartmentstate":
                this.AssertValueNotAssigned("pssessionthreadapartmentstate", (object)this.ShellThreadApartmentState);
                this.ShellThreadApartmentState = new ApartmentState?((ApartmentState)LanguagePrimitives.ConvertTo((object)optionValue, typeof(ApartmentState), (IFormatProvider)CultureInfo.InvariantCulture));
                break;
            }
        }
Esempio n. 10
0
        private void Update(string optionName, string optionValue)
        {
            switch (optionName.ToLower(CultureInfo.InvariantCulture))
            {
                case "applicationbase":
                    this.AssertValueNotAssigned("applicationbase", this.ApplicationBase);
                    this.ApplicationBase = Environment.ExpandEnvironmentVariables(optionValue);
                    return;

                case "assemblyname":
                    this.AssertValueNotAssigned("assemblyname", this.AssemblyName);
                    this.AssemblyName = optionValue;
                    return;

                case "pssessionconfigurationtypename":
                    this.AssertValueNotAssigned("pssessionconfigurationtypename", this.EndPointConfigurationTypeName);
                    this.EndPointConfigurationTypeName = optionValue;
                    return;

                case "startupscript":
                    this.AssertValueNotAssigned("startupscript", this.StartupScript);
                    if (!optionValue.EndsWith(".ps1", StringComparison.OrdinalIgnoreCase))
                    {
                        throw PSTraceSource.NewArgumentException("startupscript", "remotingerroridstrings", "StartupScriptNotCorrect", new object[] { "startupscript" });
                    }
                    this.StartupScript = Environment.ExpandEnvironmentVariables(optionValue);
                    return;

                case "psmaximumreceivedobjectsizemb":
                    this.AssertValueNotAssigned("psmaximumreceivedobjectsizemb", this.MaxReceivedObjectSizeMB);
                    this.MaxReceivedObjectSizeMB = GetIntValueInBytes(optionValue);
                    return;

                case "psmaximumreceiveddatasizepercommandmb":
                    this.AssertValueNotAssigned("psmaximumreceiveddatasizepercommandmb", this.MaxReceivedCommandSizeMB);
                    this.MaxReceivedCommandSizeMB = GetIntValueInBytes(optionValue);
                    return;

                case "pssessionthreadoptions":
                    this.AssertValueNotAssigned("pssessionthreadoptions", this.ShellThreadOptions);
                    this.ShellThreadOptions = new PSThreadOptions?((PSThreadOptions) LanguagePrimitives.ConvertTo(optionValue, typeof(PSThreadOptions), CultureInfo.InvariantCulture));
                    return;

                case "pssessionthreadapartmentstate":
                    this.AssertValueNotAssigned("pssessionthreadapartmentstate", this.ShellThreadApartmentState);
                    this.ShellThreadApartmentState = new ApartmentState?((ApartmentState) LanguagePrimitives.ConvertTo(optionValue, typeof(ApartmentState), CultureInfo.InvariantCulture));
                    return;

                case "sessionconfigurationdata":
                    this.AssertValueNotAssigned("sessionconfigurationdata", this.SessionConfigurationData);
                    this.SessionConfigurationData = PSSessionConfigurationData.Create(optionValue);
                    return;

                case "configfilepath":
                    this.AssertValueNotAssigned("configfilepath", this.ConfigFilePath);
                    this.ConfigFilePath = optionValue.ToString();
                    return;
            }
        }
Esempio n. 11
0
        /// <summary>
        /// Method which is intended for handling source <seealso cref="EventHandler{TEventArgs}"/> events.
        /// </summary>
        /// <param name="sender">Object which raised the event.</param>
        /// <param name="e">Information about the event.</param>
        public void EventHandler(object sender, TEventArgs e)
        {
#if PSLEGACY
            object[] variableKeys = LinqEmul.ToArray <object>(LinqEmul.Cast <object>(Variables.Keys));
#else
            object[] variableKeys = Variables.Keys.Cast <object>().ToArray();
#endif
            Dictionary <object, object> variables  = new Dictionary <object, object>();
            IDictionaryEnumerator       enumerator = Variables.GetEnumerator();
            try
            {
                while (enumerator.MoveNext())
                {
                    variables.Add(enumerator.Key, enumerator.Value);
                }
            }
            finally
            {
                if (enumerator is IDisposable)
                {
                    (enumerator as IDisposable).Dispose();
                }
            }
            PSHost host = Host;
            RunspaceConfiguration configuration  = Configuration;
            ApartmentState?       apartmentState = ApartmentState;
            PSThreadOptions?      threadOptions  = ThreadOptions;
            string initialLocation = InitialLocation;

            using (Runspace runspace = (host == null) ?
                                       ((configuration == null) ? RunspaceFactory.CreateRunspace() : RunspaceFactory.CreateRunspace(configuration)) :
                                       ((configuration == null) ? RunspaceFactory.CreateRunspace(host) : RunspaceFactory.CreateRunspace(host, configuration)))
            {
                if (apartmentState.HasValue)
                {
                    runspace.ApartmentState = apartmentState.Value;
                }
                if (threadOptions.HasValue)
                {
                    runspace.ThreadOptions = threadOptions.Value;
                }
                runspace.Open();

                foreach (object key in variables.Keys)
                {
                    string s = (key is string) ? key as string : key.ToString();
                    if (Variables[key] != null && String.Compare(s, "this", true) != 0 && String.Compare(s, "SynchronizedData", true) != 0)
                    {
                        runspace.SessionStateProxy.SetVariable(s, Variables[key]);
                    }
                }

                runspace.SessionStateProxy.SetVariable("this", This);
                runspace.SessionStateProxy.SetVariable("SynchronizedData", SynchronizedData);

                if (initialLocation.Length > 0)
                {
                    runspace.SessionStateProxy.Path.SetLocation(initialLocation);
                }

                using (PowerShell powerShell = PowerShell.Create())
                {
                    powerShell.Runspace = runspace;
                    RaiseEventHandlerInvoked(sender, e, new PSInvocationResult(HandlerScript.ToString(), this, powerShell, variableKeys, sender, e));
                }
            }
        }
Esempio n. 12
0
        public SingleThreadedRelayQueueWorkerProceedAllItemsBeforeStopNoLog(string name, Action <TItem> action, ThreadPriority threadPriority, bool markThreadAsBackground, ApartmentState?apartmentState)
        {
            _syncRunFlags    = new object();
            _syncUserActions = new object();

            _items  = new ConcurrentQueue <TItem>();
            _name   = name;
            _action = action ?? throw new ArgumentNullException(nameof(action));

            _threadNotifyAboutQueueItemsCountChanged = new AutoResetEvent(false);

            _isRunning     = true;
            _mustBeStopped = false;

            _workThread = new Thread(WorkingThreadStart)
            {
                IsBackground = markThreadAsBackground, Priority = threadPriority, Name = name
            };
            if (apartmentState.HasValue)
            {
                _workThread.SetApartmentState(apartmentState.Value);
            }
            _workThread.Start();
        }
        public SingleThreadPriorityAsyncStarter(string name, ThreadPriority threadPriority, bool markThreadAsBackground, ApartmentState?apartmentState, ILoggerWithStackTrace debugLogger, int maxFlow, int queuesCount, bool isWaitAllTasksCompleteNeededOnStop)
        {
            _name        = name;
            _debugLogger = debugLogger ?? throw new ArgumentNullException(nameof(debugLogger));
            _maxFlow     = maxFlow;
            _isWaitAllTasksCompleteNeededOnStop = isWaitAllTasksCompleteNeededOnStop;

            _flowCounter            = new WaitableCounter();
            _asyncActionQueueWorker = new SingleThreadedRelayMultiQueueWorker <Action>(_name, a => a(), threadPriority, markThreadAsBackground, apartmentState, debugLogger, queuesCount);
        }
        public WorkerSingleThreadedRelayDrop(Action <TItem> action, ThreadPriority threadPriority, bool markThreadAsBackground, ApartmentState?apartmentState)
        {
            _sync   = new object();
            _action = action;

            _signal = new ManualResetEvent(false);

            _isRunning     = true;
            _mustBeStopped = false;

            _workThread = new Thread(WorkingThreadStart)
            {
                IsBackground = markThreadAsBackground, Priority = threadPriority
            };
            if (apartmentState.HasValue)
            {
                _workThread.SetApartmentState(apartmentState.Value);
            }
            _workThread.Start();
        }
Esempio n. 15
0
 public Dispatcher(	int threadCount, ThreadPriority priority, DispatcherOptions options, ApartmentState threadApartmentState, string threadPoolName)
     : this(threadCount, priority, options, threadPoolName)
 {
     this.state = threadApartmentState;
 }
Esempio n. 16
0
        public SingleThreadedRelayMultiQueueWorkerExceptionless(string name, Action <TItem> action, ThreadPriority threadPriority, bool markThreadAsBackground, ApartmentState?apartmentState, ILoggerWithStackTrace debugLogger, int queuesCount)
        {
            _syncRunFlags    = new object();
            _syncUserActions = new object();

            _name        = name;
            _action      = action ?? throw new ArgumentNullException(nameof(action));
            _debugLogger = debugLogger ?? throw new ArgumentNullException(nameof(debugLogger));

            _threadNotifyAboutQueueItemsCountChanged = new AutoResetEvent(false);

            _items = new ConcurrentQueueWithPriority <TItem>(queuesCount);

            _isRunning     = true;
            _mustBeStopped = false;

            _workThread = new Thread(WorkingThreadStart)
            {
                Priority = threadPriority, IsBackground = markThreadAsBackground, Name = name
            };
            if (apartmentState.HasValue)
            {
                _workThread.SetApartmentState(apartmentState.Value);
            }
            _workThread.Start();
        }
 public SingleThreadAsyncStarterWithFlowControl(int maxFlow, ThreadPriority threadPriority, bool markThreadAsBackground, ApartmentState?apartmentState)
 {
     _maxFlow                = maxFlow;
     _flowCounter            = new WaitableCounter();
     _asyncActionQueueWorker = new SingleThreadedRelayQueueWorker <Action>(a => a(), threadPriority, markThreadAsBackground, apartmentState);
 }
        public SingleThreadedRelayQueueWorker(Action <TItem> action, ThreadPriority threadPriority, bool markThreadAsBackground, ApartmentState?apartmentState)
        {
            _items  = new ConcurrentQueue <TItem>();
            _action = action;

            _counter = new WaitableCounter();             // свой счетчик с методами ожидания

            _workThread = new Thread(WorkingThreadStart)
            {
                IsBackground = markThreadAsBackground, Priority = threadPriority
            };
            if (apartmentState.HasValue)
            {
                _workThread.SetApartmentState(apartmentState.Value);
            }
            _workThread.Start();
        }