protected WorkerThread(string name, ThreadPriority priority, ApartmentState apartmentState) { _thread = new Thread(new ThreadStart(this.InternalRun)); _thread.Name = name; _thread.Priority = priority; _thread.SetApartmentState(apartmentState); }
/// <summary> /// Runs in the specified apartment /// </summary> private void RunInApartment(ThreadStart userDelegate, ApartmentState apartmentState) { Exception thrownException = null; Thread thread = new Thread( delegate() { try { userDelegate.Invoke(); } catch (Exception e) { thrownException = e; } }); thread.SetApartmentState(apartmentState); thread.Start(); thread.Join(); if (thrownException != null) { ThrowExceptionPreservingStack(thrownException); } }
private void Run(ThreadStart userDelegate, ApartmentState apartmentState) { lastException = null; var thread = new Thread( delegate() { try { userDelegate.Invoke(); } catch (Exception e) { lastException = e; } }); thread.SetApartmentState(apartmentState); thread.Start(); thread.Join(); if (ExceptionWasThrown()) { ThrowExceptionPreservingStack(lastException); } }
public AssemblyItem( string path, ApartmentState apartment ) { if ( !System.IO.Path.IsPathRooted( path ) ) throw new ArgumentException( "Assembly path must be absolute", "path" ); this.path = path; this.apartment = apartment; }
/// <summary> /// A common helper method that tests running a test in an apartment from an apartment. /// </summary> private bool RunInApartmentFromApartment(ApartmentState fromApartMent, ApartmentState inApartment) { bool wasRunInCorrectApartment = false; Thread runnerThread = new Thread((ThreadStart)delegate { if (inApartment == ApartmentState.MTA) { ThreadRunner.RunInMTA(delegate { wasRunInCorrectApartment = Thread.CurrentThread.GetApartmentState() == inApartment; }); } else if (inApartment == ApartmentState.STA) { ThreadRunner.RunInSTA(delegate { wasRunInCorrectApartment = Thread.CurrentThread.GetApartmentState() == inApartment; }); } } ); runnerThread.SetApartmentState(fromApartMent); runnerThread.Start(); runnerThread.Join(); return wasRunInCorrectApartment; }
/// <summary>Invokes the specified delegate with the specified parameters in the specified kind of apartment state.</summary> /// <param name="d">The delegate to be invoked.</param> /// <param name="parameters">The parameters to pass to the delegate being invoked.</param> /// <param name="state">The apartment state to run under.</param> /// <returns>The result of calling the delegate.</returns> public static object Execute( Delegate d, object[] parameters, ApartmentState state) { if (d == null) throw new ArgumentNullException("d"); if (state != ApartmentState.MTA && state != ApartmentState.STA) throw new ArgumentOutOfRangeException("state"); if (Thread.CurrentThread.ApartmentState == state) { return d.DynamicInvoke(parameters); } else { ApartmentStateSwitcher switcher = new ApartmentStateSwitcher(); switcher._delegate = d; switcher._parameters = parameters; Thread t = new Thread(new ThreadStart(switcher.Run)); t.ApartmentState = state; t.IsBackground = true; t.Start(); t.Join(); if (switcher._exc != null) throw switcher._exc; return switcher._rv; } }
private void Run(ThreadStart userDelegate, ApartmentState apartmentState) { lastException = null; Thread thread = new Thread( delegate() { #if !DEBUG try { #endif userDelegate.Invoke(); #if !DEBUG } catch (Exception e) { lastException = e; } #endif }); thread.SetApartmentState(apartmentState); thread.Start(); thread.Join(); if (ExceptionWasThrown()) ThrowExceptionPreservingStack(lastException); }
internal ServerSteppablePipelineDriver(PowerShell powershell, bool noInput, Guid clientPowerShellId, Guid clientRunspacePoolId, ServerRunspacePoolDriver runspacePoolDriver, ApartmentState apartmentState, HostInfo hostInfo, System.Management.Automation.RemoteStreamOptions streamOptions, bool addToHistory, Runspace rsToUse, ServerSteppablePipelineSubscriber eventSubscriber, PSDataCollection<object> powershellInput) { this.localPowerShell = powershell; this.clientPowerShellId = clientPowerShellId; this.clientRunspacePoolId = clientRunspacePoolId; this.remoteStreamOptions = streamOptions; this.apartmentState = apartmentState; this.noInput = noInput; this.addToHistory = addToHistory; this.eventSubscriber = eventSubscriber; this.powershellInput = powershellInput; this.input = new PSDataCollection<object>(); this.inputEnumerator = this.input.GetEnumerator(); this.input.ReleaseOnEnumeration = true; this.dsHandler = runspacePoolDriver.DataStructureHandler.CreatePowerShellDataStructureHandler(clientPowerShellId, clientRunspacePoolId, this.remoteStreamOptions, null); this.remoteHost = this.dsHandler.GetHostAssociatedWithPowerShell(hostInfo, runspacePoolDriver.ServerRemoteHost); this.dsHandler.InputEndReceived += new EventHandler(this.HandleInputEndReceived); this.dsHandler.InputReceived += new EventHandler<RemoteDataEventArgs<object>>(this.HandleInputReceived); this.dsHandler.StopPowerShellReceived += new EventHandler(this.HandleStopReceived); this.dsHandler.HostResponseReceived += new EventHandler<RemoteDataEventArgs<RemoteHostResponse>>(this.HandleHostResponseReceived); this.dsHandler.OnSessionConnected += new EventHandler(this.HandleSessionConnected); if (rsToUse == null) { throw PSTraceSource.NewInvalidOperationException("RemotingErrorIdStrings", "NestedPipelineMissingRunspace", new object[0]); } this.localPowerShell.Runspace = rsToUse; eventSubscriber.SubscribeEvents(this); this.stateOfSteppablePipeline = PSInvocationState.NotStarted; }
/// <summary> /// Class constructor initializes fields from config file /// </summary> static NUnitConfiguration() { try { NameValueCollection settings = GetConfigSection("NUnit/TestCaseBuilder"); if (settings != null) { string oldStyle = settings["OldStyleTestCases"]; if (oldStyle != null) allowOldStyleTests = Boolean.Parse(oldStyle); } settings = GetConfigSection("NUnit/TestRunner"); if (settings != null) { string apartment = settings["ApartmentState"]; if (apartment != null) apartmentState = (ApartmentState) System.Enum.Parse(typeof(ApartmentState), apartment, true); string priority = settings["ThreadPriority"]; if (priority != null) threadPriority = (ThreadPriority) System.Enum.Parse(typeof(ThreadPriority), priority, true); } } catch (Exception ex) { string msg = string.Format("Invalid configuration setting in {0}", AppDomain.CurrentDomain.SetupInformation.ConfigurationFile); throw new ApplicationException(msg, ex); } }
/// <summary> /// Initialies a new <see cref="DispatcherContext"/> synchronized with a new <see cref="Thread"/> instance /// </summary> /// <param name="threadApartmentState">The <see cref="ApartmentState"/> of the <see cref="Dispatcher"/>'s <see cref="Thread"/></param> ///<param name="owner">The <see cref="Dispatcher"/> that owns the <see cref="DispatcherContext"/></param> public DispatcherContext(Dispatcher owner, ApartmentState threadApartmentState) { Thread dispatcherThread; this.Owner = owner; dispatcherThread = new Thread(new ParameterizedThreadStart(this.ExecuteOperations)); dispatcherThread.SetApartmentState(threadApartmentState); }
public SingleThreadTaskScheduler(string name = null, ThreadPriority priority = ThreadPriority.Normal, ApartmentState apartmentState = ApartmentState.STA) { #if DEBUG _allocStackTrace = new StackTrace(); #endif _thread = new Thread( () => { try { foreach (var task in _queue.GetConsumingEnumerable()) TryExecuteTask(task); } finally { _queue.Dispose(); } }); _thread.IsBackground = true; _thread.Name = name; _thread.Priority = priority; _thread.SetApartmentState(apartmentState); _thread.Start(); }
private void StartNewDispatcherThread(ApartmentState apartmentState) { var reset = new ManualResetEvent(false); var t = new Thread((ThreadStart)delegate { Thread.CurrentThread.Name = string.Format("WorkDispatcherThread"); Dispatcher.Run(reset); }) { IsBackground = true }; t.SetApartmentState(apartmentState); t.Priority = ThreadPriority.Normal; /* Starts the thread and creates the object */ t.Start(); /* We wait until our dispatcher is initialized and * the new Dispatcher is running */ reset.WaitOne(); }
public void GetParentThreadInfo() { ParentThread = Thread.CurrentThread; #if !NETCF ParentThreadApartment = GetApartmentState(ParentThread); #endif }
private void InitializeThreadState(object threadParams, ThreadWorkerMethodWithReturn workerMethod, ApartmentState aptState, bool background) { this.threadParams = threadParams; this.threadWorkerMethodWithReturn = workerMethod; this.thread = new Thread(new ThreadStart(this.ThreadEntryPointMethodWithReturn)); this.thread.SetApartmentState(aptState); this.backgroundThread = background; }
private IRSPDriverInvoke _psDriverInvoker; // Handles nested invocation of PS drivers. #endregion Private Members #region Constructors #if !CORECLR /// <summary> /// Default constructor for creating ServerPowerShellDrivers /// </summary> /// <param name="powershell">decoded powershell object</param> /// <param name="extraPowerShell">extra pipeline to be run after <paramref name="powershell"/> completes</param> /// <param name="noInput">whether there is input for this powershell</param> /// <param name="clientPowerShellId">the client powershell id</param> /// <param name="clientRunspacePoolId">the client runspacepool id</param> /// <param name="runspacePoolDriver">runspace pool driver /// which is creating this powershell driver</param> /// <param name="apartmentState">apartment state for this powershell</param> /// <param name="hostInfo">host info using which the host for /// this powershell will be constructed</param> /// <param name="streamOptions">serialization options for the streams in this powershell</param> /// <param name="addToHistory"> /// true if the command is to be added to history list of the runspace. false, otherwise. /// </param> /// <param name="rsToUse"> /// If not null, this Runspace will be used to invoke Powershell. /// If null, the RunspacePool pointed by <paramref name="runspacePoolDriver"/> will be used. /// </param> internal ServerPowerShellDriver(PowerShell powershell, PowerShell extraPowerShell, bool noInput, Guid clientPowerShellId, Guid clientRunspacePoolId, ServerRunspacePoolDriver runspacePoolDriver, ApartmentState apartmentState, HostInfo hostInfo, RemoteStreamOptions streamOptions, bool addToHistory, Runspace rsToUse) : this(powershell, extraPowerShell, noInput, clientPowerShellId, clientRunspacePoolId, runspacePoolDriver, apartmentState, hostInfo, streamOptions, addToHistory, rsToUse, null) { }
/// <summary> /// Construct a new TestWorker. /// </summary> /// <param name="queue">The queue from which to pull work items</param> /// <param name="name">The name of this worker</param> /// <param name="apartmentState">The apartment state to use for running tests</param> public TestWorker(WorkItemQueue queue, string name, ApartmentState apartmentState) { _readyQueue = queue; _workerThread = new Thread(new ThreadStart(TestWorkerThreadProc)); _workerThread.Name = name; _workerThread.SetApartmentState(apartmentState); }
public DedicatedThreadPoolSettings(int numThreads, string name = null, TimeSpan? deadlockTimeout = null, ApartmentState apartmentState = ApartmentState.Unknown, Action<Exception> exceptionHandler = null, int threadMaxStackSize = 0) : this(numThreads, DefaultThreadType, name, deadlockTimeout, apartmentState, exceptionHandler, threadMaxStackSize) { }
public void Start(ApartmentState state = ApartmentState.MTA) { if (thread == null) { thread = new Thread(WorkThread); thread.SetApartmentState(state); thread.Start(); } }
public BackgroundWorker(IPendingWorkCollection<IScheduledTask> pendingWorkCollection, ApartmentState apartmentState) { _cancellationTokenSource = new CancellationTokenSource(); _pendingWorkCollection = pendingWorkCollection; _apartmentState = apartmentState; _isDisposing = false; _isDisposed = false; _isStarted = false; }
public ExecutionQueue(ApartmentState state) { _executionThread = new Thread(ExecutionThread); _executionThread.IsBackground = true; _executionThread.Name = "ExecutionThread"; _executionThread.SetApartmentState(state); _executionThread.Start(); _commandDispatcher = (action) => action(); }
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; }
/// <summary> /// Evaluates expression within the given environment on /// a new thread - Returns immediately, but the new thread /// continues to execute expression asynchronously. /// </summary> /// <param name="expression"></param> /// <param name="environment"></param> /// <returns>The new Thread</returns> public static Thread Fork(Object expression, Environment environment, ApartmentState apartmentState) { ThreadAdapter threadAdapter = new ThreadAdapter(expression, environment); ThreadStart job = new ThreadStart(threadAdapter.Invoke); Thread thread = new Thread(job); thread.SetApartmentState(apartmentState); thread.Start(); return thread; }
/// <summary> /// Runs the specified delegate in the specified apartment /// </summary> private static void RunInApartment(ThreadStart userDelegate, ApartmentState apartment) { if (apartment == ApartmentState.Unknown) { throw new InvalidOperationException("Can only run in STAs or MTAs"); } ApartmentOperationRunner runner = new ApartmentOperationRunner(); runner.Run(userDelegate, apartment); }
/// <summary> /// Initializes a new instance of the <see cref="ThreadedWorkerBase" /> class. /// </summary> /// <param name="logger">The logger.</param> /// <param name="apartmentState"></param> /// <param name="isBackgroundThread">Specifies whether or not the thread should be marked as a Background Thread</param> protected ThreadedWorkerBase(ILogger logger, ApartmentState apartmentState = ApartmentState.MTA, bool isBackgroundThread = true) { this.logger = Guard.IsNull(() => logger); Id = Guid.NewGuid(); thread = new Thread(DoExecute) { IsBackground = isBackgroundThread }; thread.SetApartmentState(apartmentState); }
public void append(BackgroundWorkerItem item, Object[] parameters, TimeSpan timeout, ApartmentState apartmentState, ThreadPriority priority) { StackItem sItem = new StackItem(); sItem.bWItem = item; sItem.parameters = parameters; sItem.timeout = timeout; sItem.apartmentState = apartmentState; sItem.priority = priority; // this._methodStack.Add(sItem); }
internal PipelineThread(ApartmentState apartmentState) { this.worker = new Thread(new ThreadStart(this.WorkerProc), LocalPipeline.MaxStack); this.workItem = null; this.workItemReady = new AutoResetEvent(false); this.closed = false; if (apartmentState != ApartmentState.Unknown) { this.worker.SetApartmentState(apartmentState); } }
public int Run(string[] arguments, Configuration configuration, ProgressReporter reporter) { LastArguments = arguments; ApartmentState = Thread.CurrentThread.GetApartmentState(); try { return int.Parse(ConfigurationManager.AppSettings.Get("returnCode")); } catch (Exception) { return Result; } }
public static Thread AlterThread(Action action, bool isBackground, ApartmentState apartmentState) { Thread t = new Thread(() => { action(); }); t.SetApartmentState(apartmentState); t.IsBackground = isBackground; t.Start(); return t; }
/// <summary> /// 创建线程 /// </summary> /// <param name="name"></param> /// <param name="task"></param> /// <param name="isBackground"></param> /// <param name="apartmentState"></param> public SmartThread(Action task, string name = null, bool isBackground = true, ApartmentState apartmentState = ApartmentState.MTA) { if (task == null) throw new ArgumentNullException("task"); InnerThread = new System.Threading.Thread(()=>task()) { Name = name, IsBackground = isBackground }; InnerThread.SetApartmentState(apartmentState); mutex = new ResetEvent(false); State = ThreadState.NotStarted; }
public void SetApartmentState(ApartmentState state) { try { thread.SetApartmentState(state); } catch (Exception exception) { if (logger != null) logger.Log("HomeOS SafeThread exception in setapartmentstate() : " + exception.GetType()); } }
/// <summary> /// Sets the threading apartment state of the Thread. This must be called before starting the thread /// </summary> /// <param name="state">The new state</param> public void SetApartmentState(ApartmentState state) { _thread.SetApartmentState(state); }
/// <summary> /// Performs the update. /// </summary> /// <returns><c>true</c> if the update completed successfully; /// <c>false</c> otherwise.</returns> public override bool Update() { Trace.TraceInformation("Checking for new client version..."); Trace.Indent(); SetProgressMaximum(2); SetMessage(String.Format("Checking for new {0} version...", EnvironmentInfo.Settings.ModManagerName)); string strDownloadUri = String.Empty; Version verNew = GetNewProgrammeVersion(out strDownloadUri); SetProgress(1); if (CancelRequested) { Trace.Unindent(); return(CancelUpdate()); } if (verNew == new Version("69.69.69.69")) { SetMessage("Could not get version information from the update server."); return(false); } StringBuilder stbPromptMessage = new StringBuilder(); DialogResult drResult = DialogResult.No; string strReleaseNotes = String.Empty; if ((verNew > new Version(ProgrammeMetadata.VersionString)) && !String.IsNullOrEmpty(strDownloadUri)) { string strCheckDownloadedInstaller = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "Temp", Path.GetFileName(strDownloadUri)); stbPromptMessage.AppendFormat("A new version of {0} is available ({1}).{2}Would you like to download and install it?", EnvironmentInfo.Settings.ModManagerName, verNew, Environment.NewLine).AppendLine(); stbPromptMessage.AppendLine(); stbPromptMessage.AppendLine(); stbPromptMessage.AppendLine("Below you can find the change log for the new release:"); try { HttpWebRequest request = (HttpWebRequest)WebRequest.Create(m_strURI); HttpWebResponse response = (HttpWebResponse)request.GetResponse(); if (response.StatusCode == HttpStatusCode.OK) { Stream receiveStream = response.GetResponseStream(); StreamReader readStream = null; if (response.CharacterSet == null) { readStream = new StreamReader(receiveStream); } else { readStream = new StreamReader(receiveStream, Encoding.GetEncoding(response.CharacterSet)); } strReleaseNotes = readStream.ReadToEnd(); response.Close(); readStream.Close(); } } catch { strReleaseNotes = "Unable to retrieve the Release Notes."; } try { //the extended message box contains an activex control wich must be run in an STA thread, // we can't control what thread this gets called on, so create one if we need to ThreadStart actShowMessage = () => drResult = ExtendedMessageBox.Show(null, stbPromptMessage.ToString(), "New version available", strReleaseNotes, 700, 450, ExtendedMessageBoxButtons.Backup, MessageBoxIcon.Question); ApartmentState astState = ApartmentState.Unknown; Thread.CurrentThread.TrySetApartmentState(astState); if (astState == ApartmentState.STA) { actShowMessage(); } else { Thread thdMessage = new Thread(actShowMessage); thdMessage.SetApartmentState(ApartmentState.STA); thdMessage.Start(); thdMessage.Join(); } } catch { } if (drResult == DialogResult.Cancel) { Trace.Unindent(); return(CancelUpdate()); } if (drResult == DialogResult.Yes) { UpdateManager.CreateBackup(); } if (File.Exists(strCheckDownloadedInstaller)) { SetMessage("Launching installer..."); ProcessStartInfo psiInfo = new ProcessStartInfo(strCheckDownloadedInstaller); Process.Start(psiInfo); Trace.Unindent(); return(true); } SetMessage(String.Format("Downloading new {0} version...", EnvironmentInfo.Settings.ModManagerName)); string strNewInstaller = string.Empty; try { strNewInstaller = DownloadFile(new Uri(String.Format(strDownloadUri))); } catch (FileNotFoundException) { StringBuilder stbAVMessage = new StringBuilder(); stbAVMessage.AppendLine("Unable to find the installer to download:"); stbAVMessage.AppendLine("this could be caused by a network issue or by your Firewall."); stbAVMessage.AppendLine("As a result you won't be able to automatically update the program."); stbAVMessage.AppendLine(); stbAVMessage.AppendFormat("You can download the update manually from:"); stbAVMessage.AppendLine("http://skyrim.nexusmods.com/mods/modmanager/"); try { //the extended message box contains an activex control wich must be run in an STA thread, // we can't control what thread this gets called on, so create one if we need to ThreadStart actShowMessage = () => drResult = ExtendedMessageBox.Show(null, stbAVMessage.ToString(), "Unable to update", MessageBoxButtons.OK, MessageBoxIcon.Information); ApartmentState astState = ApartmentState.Unknown; Thread.CurrentThread.TrySetApartmentState(astState); if (astState == ApartmentState.STA) { actShowMessage(); } else { Thread thdMessage = new Thread(actShowMessage); thdMessage.SetApartmentState(ApartmentState.STA); thdMessage.Start(); thdMessage.Join(); } } catch { } Trace.Unindent(); return(CancelUpdate()); } SetProgress(2); if (CancelRequested) { Trace.Unindent(); return(CancelUpdate()); } if (!String.IsNullOrEmpty(strNewInstaller)) { string strOldPath = strNewInstaller; strNewInstaller = Path.Combine(Path.GetTempPath(), Path.GetFileName(strNewInstaller)); FileUtil.ForceDelete(strNewInstaller); try { File.Move(strOldPath, strNewInstaller); } catch (FileNotFoundException) { StringBuilder stbAVMessage = new StringBuilder(); stbAVMessage.AppendLine("Unable to find the downloaded update:"); stbAVMessage.AppendLine("this could be caused by a network issue or by your anti-virus software deleting it falsely flagging the installer as a virus."); stbAVMessage.AppendLine("As a result you won't be able to automatically update the program."); stbAVMessage.AppendLine(); stbAVMessage.AppendFormat("To fix this issue you need to add {0}'s executable and all its folders to your", EnvironmentInfo.Settings.ModManagerName).AppendLine(); stbAVMessage.AppendLine("anti-virus exception list. You can also download the update manually from:"); stbAVMessage.AppendLine("http://skyrim.nexusmods.com/mods/modmanager/"); try { //the extended message box contains an activex control wich must be run in an STA thread, // we can't control what thread this gets called on, so create one if we need to ThreadStart actShowMessage = () => drResult = ExtendedMessageBox.Show(null, stbAVMessage.ToString(), "Unable to update", MessageBoxButtons.OK, MessageBoxIcon.Information); ApartmentState astState = ApartmentState.Unknown; Thread.CurrentThread.TrySetApartmentState(astState); if (astState == ApartmentState.STA) { actShowMessage(); } else { Thread thdMessage = new Thread(actShowMessage); thdMessage.SetApartmentState(ApartmentState.STA); thdMessage.Start(); thdMessage.Join(); } } catch { } Trace.Unindent(); return(CancelUpdate()); } SetMessage("Launching installer..."); ProcessStartInfo psiInfo = new ProcessStartInfo(strNewInstaller); Process.Start(psiInfo); Trace.Unindent(); return(true); } } else if (!m_booIsAutoCheck) { stbPromptMessage.AppendFormat("{0} is already up to date.", EnvironmentInfo.Settings.ModManagerName).AppendLine(); stbPromptMessage.AppendLine(); stbPromptMessage.AppendLine(); stbPromptMessage.AppendLine("NOTE: You can find the release notes, planned features and past versions here:"); stbPromptMessage.AppendLine("http://forums.nexusmods.com/index.php?/topic/896029-nexus-mod-manager-release-notes/"); try { //the extended message box contains an activex control wich must be run in an STA thread, // we can't control what thread this gets called on, so create one if we need to ThreadStart actShowMessage = () => drResult = ExtendedMessageBox.Show(null, stbPromptMessage.ToString(), "Up to date", MessageBoxButtons.OK, MessageBoxIcon.Information); ApartmentState astState = ApartmentState.Unknown; Thread.CurrentThread.TrySetApartmentState(astState); if (astState == ApartmentState.STA) { actShowMessage(); } else { Thread thdMessage = new Thread(actShowMessage); thdMessage.SetApartmentState(ApartmentState.STA); thdMessage.Start(); thdMessage.Join(); } } catch { } } SetMessage(String.Format("{0} is already up to date.", EnvironmentInfo.Settings.ModManagerName)); SetProgress(2); Trace.Unindent(); return(true); }
private ISynchronizedThread StartSynchronizedThread(ThreadStart threadMethod, string threadName, ApartmentState state) { _logger.Debug($"Starting {threadName} thread"); var t = new SynchronizedThread(threadMethod); t.Name = threadName; t.SetApartmentState(state); StartSynchronizedThread(t); return(t); }
public void GetsTargetApartmentFromParentTests(Test test, ApartmentState expected) { var work = new FakeWorkItem(test, TestFilter.Empty); Assert.That(work.TargetApartment, Is.EqualTo(expected)); }
/// <summary> /// Initializes a new instance of the <see cref="ThreadedWorker" /> class. /// </summary> /// <param name="target">The target.</param> /// <param name="logger">The logger.</param> /// <param name="apartmentState">State of the apartment.</param> public ThreadedWorker(Action target, ILogger logger, ApartmentState apartmentState) : base(logger, apartmentState) { target.Guard("target"); this.target = target; }
/// <summary> /// Default constructor for creating ServerPowerShellDrivers /// </summary> /// <param name="powershell">Decoded powershell object.</param> /// <param name="extraPowerShell">Extra pipeline to be run after <paramref name="powershell"/> completes.</param> /// <param name="noInput">Whether there is input for this powershell.</param> /// <param name="clientPowerShellId">The client powershell id.</param> /// <param name="clientRunspacePoolId">The client runspacepool id.</param> /// <param name="runspacePoolDriver">runspace pool driver /// which is creating this powershell driver</param> /// <param name="apartmentState">Apartment state for this powershell.</param> /// <param name="hostInfo">host info using which the host for /// this powershell will be constructed</param> /// <param name="streamOptions">Serialization options for the streams in this powershell.</param> /// <param name="addToHistory"> /// true if the command is to be added to history list of the runspace. false, otherwise. /// </param> /// <param name="rsToUse"> /// If not null, this Runspace will be used to invoke Powershell. /// If null, the RunspacePool pointed by <paramref name="runspacePoolDriver"/> will be used. /// </param> /// <param name="output"> /// If not null, this is used as another source of output sent to the client. /// </param> internal ServerPowerShellDriver(PowerShell powershell, PowerShell extraPowerShell, bool noInput, Guid clientPowerShellId, Guid clientRunspacePoolId, ServerRunspacePoolDriver runspacePoolDriver, ApartmentState apartmentState, HostInfo hostInfo, RemoteStreamOptions streamOptions, bool addToHistory, Runspace rsToUse, PSDataCollection <PSObject> output) #endif { InstanceId = clientPowerShellId; RunspacePoolId = clientRunspacePoolId; RemoteStreamOptions = streamOptions; #if !CORECLR // No ApartmentState In CoreCLR this.apartmentState = apartmentState; #endif LocalPowerShell = powershell; _extraPowerShell = extraPowerShell; _localPowerShellOutput = new PSDataCollection <PSObject>(); _noInput = noInput; _addToHistory = addToHistory; _psDriverInvoker = runspacePoolDriver; DataStructureHandler = runspacePoolDriver.DataStructureHandler.CreatePowerShellDataStructureHandler(clientPowerShellId, clientRunspacePoolId, RemoteStreamOptions, LocalPowerShell); _remoteHost = DataStructureHandler.GetHostAssociatedWithPowerShell(hostInfo, runspacePoolDriver.ServerRemoteHost); if (!noInput) { InputCollection = new PSDataCollection <object>(); InputCollection.ReleaseOnEnumeration = true; InputCollection.IdleEvent += new EventHandler <EventArgs>(HandleIdleEvent); } RegisterPipelineOutputEventHandlers(_localPowerShellOutput); if (LocalPowerShell != null) { RegisterPowerShellEventHandlers(LocalPowerShell); _datasent[0] = false; } if (extraPowerShell != null) { RegisterPowerShellEventHandlers(extraPowerShell); _datasent[1] = false; } RegisterDataStructureHandlerEventHandlers(DataStructureHandler); // set the runspace pool and invoke this powershell if (rsToUse != null) { LocalPowerShell.Runspace = rsToUse; if (extraPowerShell != null) { extraPowerShell.Runspace = rsToUse; } } else { LocalPowerShell.RunspacePool = runspacePoolDriver.RunspacePool; if (extraPowerShell != null) { extraPowerShell.RunspacePool = runspacePoolDriver.RunspacePool; } } if (output != null) { output.DataAdded += (sender, args) => { if (_localPowerShellOutput.IsOpen) { var items = output.ReadAll(); foreach (var item in items) { _localPowerShellOutput.Add(item); } } }; } }
internal ServerPowerShellDriver(PowerShell powershell, PowerShell extraPowerShell, bool noInput, Guid clientPowerShellId, Guid clientRunspacePoolId, ServerRunspacePoolDriver runspacePoolDriver, ApartmentState apartmentState, HostInfo hostInfo, System.Management.Automation.RemoteStreamOptions streamOptions, bool addToHistory, Runspace rsToUse) { this.clientPowerShellId = clientPowerShellId; this.clientRunspacePoolId = clientRunspacePoolId; this.remoteStreamOptions = streamOptions; this.apartmentState = apartmentState; this.localPowerShell = powershell; this.extraPowerShell = extraPowerShell; this.localPowerShellOutput = new PSDataCollection <PSObject>(); this.noInput = noInput; this.addToHistory = addToHistory; this.dsHandler = runspacePoolDriver.DataStructureHandler.CreatePowerShellDataStructureHandler(clientPowerShellId, clientRunspacePoolId, this.remoteStreamOptions, this.localPowerShell); this.remoteHost = this.dsHandler.GetHostAssociatedWithPowerShell(hostInfo, runspacePoolDriver.ServerRemoteHost); if (!noInput) { this.input = new PSDataCollection <object>(); this.input.ReleaseOnEnumeration = true; this.input.IdleEvent += new EventHandler <EventArgs>(this.HandleIdleEvent); } this.RegisterPipelineOutputEventHandlers(this.localPowerShellOutput); if (this.localPowerShell != null) { this.RegisterPowerShellEventHandlers(this.localPowerShell); this.datasent[0] = false; } if (extraPowerShell != null) { this.RegisterPowerShellEventHandlers(extraPowerShell); this.datasent[1] = false; } this.RegisterDataStructureHandlerEventHandlers(this.dsHandler); if (rsToUse != null) { this.localPowerShell.Runspace = rsToUse; if (extraPowerShell != null) { extraPowerShell.Runspace = rsToUse; } } else { this.localPowerShell.RunspacePool = runspacePoolDriver.RunspacePool; if (extraPowerShell != null) { extraPowerShell.RunspacePool = runspacePoolDriver.RunspacePool; } } }
/// <summary> /// This lets the user know a problem has occurred, and logs the exception. /// </summary> /// <param name="ex">The exception that is being handled.</param> private static void HandleException(Exception ex) { HeaderlessTextWriterTraceListener htlListener = (HeaderlessTextWriterTraceListener)Trace.Listeners["DefaultListener"]; DialogResult drResult = DialogResult.No; Trace.WriteLine(""); Trace.TraceError("Tracing an Unhandled Exception:"); TraceUtil.TraceException(ex); if (!htlListener.TraceIsForced) { htlListener.SaveToFile(); } StringBuilder stbPromptMessage = new StringBuilder(); stbPromptMessage.AppendFormat("{0} has encountered an error and needs to close.", EnvironmentInfo.Settings.ModManagerName).AppendLine(); stbPromptMessage.AppendLine("A Trace Log file was created at:"); stbPromptMessage.AppendLine(htlListener.FilePath); stbPromptMessage.AppendLine("Before reporting the issue, don't close this window and check for a fix here (you can close it afterwards):"); stbPromptMessage.AppendLine(NexusLinks.FAQs); stbPromptMessage.AppendLine("If you can't find a solution, please make a bug report and attach the TraceLog file here:"); stbPromptMessage.AppendLine(NexusLinks.Issues); stbPromptMessage.AppendLine(Environment.NewLine + "Do you want to open the TraceLog folder?"); try { //the extended message box contains an activex control wich must be run in an STA thread, // we can't control what thread this gets called on, so create one if we need to string strException = "The following information is in the Trace Log:" + Environment.NewLine + TraceUtil.CreateTraceExceptionString(ex); ThreadStart actShowMessage = () => drResult = ExtendedMessageBox.Show(null, stbPromptMessage.ToString(), "Error", strException, MessageBoxButtons.YesNo, MessageBoxIcon.Information); ApartmentState astState = ApartmentState.Unknown; Thread.CurrentThread.TrySetApartmentState(astState); if (astState == ApartmentState.STA) { actShowMessage(); } else { Thread thdMessage = new Thread(actShowMessage); thdMessage.SetApartmentState(ApartmentState.STA); thdMessage.Start(); thdMessage.Join(); if (drResult == DialogResult.Yes) { try { System.Diagnostics.Process prc = new System.Diagnostics.Process(); prc.StartInfo.FileName = Path.GetDirectoryName(htlListener.FilePath); prc.Start(); } catch { } } } } catch { //backup, in case on extended message box starts to act up MessageBox.Show(stbPromptMessage.ToString(), "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); } }
public void SetApartmentState(ApartmentState aptState) { _thread.SetApartmentState(aptState); }
public void GetParentThreadInfo() { this.parentThread = Thread.CurrentThread; this.parentThreadApartment = parentThread.ApartmentState; }
public void SetApartmentState(ApartmentState state) { }
/// <summary> /// Initializes a new instance of the <see cref="ParameterizedThreadedResultWorker{TArgs,TResult}" /> class. /// </summary> /// <param name="target">The target.</param> /// <param name="logger">The logger.</param> /// <param name="apartmentState">State of the apartment.</param> /// <param name="isBackgroundThread"></param> public ParameterizedThreadedResultWorker(Func <TArgs, TResult> target, ILogger logger, ApartmentState apartmentState = ApartmentState.MTA, bool isBackgroundThread = true) : base(logger, apartmentState, isBackgroundThread) { this.target = target ?? throw new ArgumentNullException(nameof(target)); }
private static void InitializeApartmentState(ApartmentState state) { Thread.CurrentThread.SetApartmentState(state); }
/// <summary> /// Initializes a new instance of the <see cref="ForegroundThreadWithDispatcher"/> class. /// </summary> /// <param name="name">The name of the thread.</param> /// <param name="state">The apartment state of the thread.</param> /// <param name="priority">The priority of the thread.</param> public ForegroundThreadWithDispatcher([NotNull] string name, ApartmentState state, ThreadPriority priority) : base(name, state, priority, false) { ShutdownPriority = DispatcherPriority.Normal; }
public static Thread StartThread(VoidResultVoidParams function, bool background = false, ApartmentState state = ApartmentState.MTA, string threadName = "") { var thread = new Thread(new ThreadStart(function)) { IsBackground = background, Name = threadName }; thread.SetApartmentState(state); thread.Start(); return(thread); }
/// <summary> /// Initializes a new instance of the <see cref="BackgroundThreadWithDispatcher"/> class. /// </summary> /// <param name="name">The name of the thread.</param> /// <param name="state">The apartment state of the thread.</param> public BackgroundThreadWithDispatcher([NotNull] string name, ApartmentState state) : base(name, state, ThreadPriority.Normal, true) { }
/// <summary> /// Initializes a new instance of the <see cref="ForegroundThreadWithDispatcher"/> class with normal thread priority. /// </summary> /// <param name="name">The name of the thread.</param> /// <param name="state">The apartment state of the thread.</param> public ForegroundThreadWithDispatcher([NotNull] string name, ApartmentState state) : this(name, state, ThreadPriority.Normal) { Contract.Requires(!string.IsNullOrEmpty(name)); }
public void GetParentThreadInfo() { ParentThread = Thread.CurrentThread; ParentThreadApartment = GetApartmentState(ParentThread); }
/// <summary> /// Initializes a new instance of the <see cref="BackgroundThreadWithDispatcher"/> class. /// </summary> /// <param name="name">The name of the thread.</param> /// <param name="state">The apartment state of the thread.</param> /// <param name="priority">The priority of the thread.</param> public BackgroundThreadWithDispatcher([NotNull] string name, ApartmentState state, ThreadPriority priority) : base(name, state, priority, true) { Contract.Requires(!string.IsNullOrEmpty(name)); }
static ITest CreateFakeTests(ApartmentState assemblyApartment, ApartmentState fixtureApartment, ApartmentState methodApartment) => new FakeTest("Method", methodApartment) { Parent = new FakeTest("Fixture", fixtureApartment) { Parent = new FakeTest("Assembly", assemblyApartment) } };
public static Thread StartTry(Action code, ErrorHandler onError = null, Action finallyCode = null, bool background = true, ApartmentState state = ApartmentState.Unknown) { Thread t = new Thread( () => { try { code.Invoke(); } catch (ThreadAbortException) { Thread.ResetAbort(); } catch (Exception e) { try { if (onError == null) { throw e; } onError.Invoke(e); } catch (ThreadAbortException) { Thread.ResetAbort(); } } finally { finallyCode?.Invoke(); } } ); if (state != ApartmentState.Unknown) { t.SetApartmentState(state); } t.IsBackground = background; t.Start(); return(t); }
private void RunOnSeparateThread(ApartmentState apartment)
public DEThread(IServiceProvider sp, string name, ThreadDelegate action, string categoryName = ThreadCategory, ThreadPriority priority = ThreadPriority.Normal, bool isBackground = false, ApartmentState apartmentState = ApartmentState.MTA) : base(sp, name, categoryName) { this.action = action; StartThread(name, priority, isBackground, apartmentState); } // ctor
public bool TrySetApartmentStateUnchecked(ApartmentState state) => false;
public bool TrySetApartmentStateUnchecked(ApartmentState state) { return(state == GetApartmentState()); }
} // ctor protected void StartThread(string name, ThreadPriority priority = ThreadPriority.Normal, bool isBackground = false, ApartmentState apartmentState = ApartmentState.MTA) { // create the thread thread = new Thread(Execute); thread.SetApartmentState(apartmentState); thread.IsBackground = isBackground; thread.Priority = priority; thread.Name = name; // start the thread startedEvent = new ManualResetEventSlim(false); stoppingEvent = new ManualResetEventSlim(false); thread.Start(); if (!startedEvent.Wait(3000)) { throw new Exception(String.Format("Could not start thread '{0}'.", name)); } Procs.FreeAndNil(ref startedEvent); } // proc StartThread
/// <summary> /// Execute the current work item, including any /// child work items. /// </summary> public virtual void Execute() { // Timeout set at a higher level int timeout = Context.TestCaseTimeout; // Timeout set on this test if (Test.Properties.ContainsKey(PropertyNames.Timeout)) { timeout = (int)Test.Properties.Get(PropertyNames.Timeout); } // Unless the context is single threaded, a supplementary thread // is created on the various platforms... // 1. If the test used the RequiresThreadAttribute. // 2. If a test method has a timeout. // 3. If the test needs to run in a different apartment. // // NOTE: We want to eliminate or significantly reduce // cases 2 and 3 in the future. // // Case 2 requires the ability to stop and start test workers // dynamically. We would cancel the worker thread, dispose of // the worker and start a new worker on a new thread. // // Case 3 occurs when using either dispatcher whenever a // child test calls for a different apartment from the one // used by it's parent. It routinely occurs under the simple // dispatcher (--workers=0 option). Under the parallel dispatcher // it is needed when test cases are not enabled for parallel // execution. Currently, test cases are always run sequentially, // so this continues to apply fairly generally. var ownThreadReason = OwnThreadReason.NotNeeded; #if !PORTABLE if (Test.RequiresThread) { ownThreadReason |= OwnThreadReason.RequiresThread; } if (timeout > 0 && Test is TestMethod) { ownThreadReason |= OwnThreadReason.Timeout; } #if !SILVERLIGHT && !NETCF CurrentApartment = Thread.CurrentThread.GetApartmentState(); if (CurrentApartment != TargetApartment && TargetApartment != ApartmentState.Unknown) { ownThreadReason |= OwnThreadReason.DifferentApartment; } #endif #endif if (ownThreadReason == OwnThreadReason.NotNeeded) { RunTest(); } else if (Context.IsSingleThreaded) { var msg = "Test is not runnable in single-threaded context. " + ownThreadReason; log.Error(msg); Result.SetResult(ResultState.NotRunnable, msg); WorkItemComplete(); } else { log.Debug("Running test on own thread. " + ownThreadReason); #if SILVERLIGHT || NETCF RunTestOnOwnThread(timeout); #elif !PORTABLE var apartment = (ownThreadReason | OwnThreadReason.DifferentApartment) != 0 ? TargetApartment : CurrentApartment; RunTestOnOwnThread(timeout, apartment); #endif } }
private void RunTestOnOwnThread(int timeout, ApartmentState apartment) { thread = new Thread(new ThreadStart(RunTest)); thread.SetApartmentState(apartment); RunThread(timeout); }
public bool TrySetApartmentState(ApartmentState state) { }
private static bool TrySetApartmentStateUnchecked(ApartmentState state) => state == ApartmentState.Unknown;