Page 1 of 1

ThreadOptions ReuseThread not working

Posted: Wed Dec 12, 2018 11:43 am
by mmmoi5
Hi,
When I use Sapien products to generate an EXE file of the PowerShell script, the $Host.Runspace.ThreadOptions = "ReuseThread" stops working and it is reporting "The property 'ThreadOptions' cannot be found on this object. Verify that the property exists and can be set"

Is it because it is an EXE, or is there another reason ?

Thank you

Re: ThreadOptions ReuseThread not working

Posted: Fri Dec 14, 2018 7:23 am
by davidc
The host does not support / implement the Runspace property. Why do you need to change the runspace's ThreadOption?

Re: ThreadOptions ReuseThread not working

Posted: Wed Dec 19, 2018 3:29 am
by mmmoi5
When the statement is made from a PS console it works fine, it is only when passed via the EXE file that it reports what I previously stated.
Looking for an explanation to explain that behavior.

You stated that the host does not support or implement runspace property. But it does in a PS console, why not through the same PS code enveloped in an EXE ?


Thank you.

Re: ThreadOptions ReuseThread not working

Posted: Wed Jan 02, 2019 7:23 am
by davidc
The console itself is a PowerShell host as well, but when you run an executable, it is using a different host. Unfortunately, Microsoft's documentation is spare on the subject.

Re: ThreadOptions ReuseThread not working

Posted: Wed Jan 02, 2019 7:30 am
by davidc
Apparently this property is not exposed to third party hosts. It is internal to PowerShell.

Re: ThreadOptions ReuseThread not working

Posted: Wed Jan 02, 2019 8:01 am
by jvierra
"ReuseThread" can only be set before the runspace is created. Once it is created and a thread is allocated the property is read-only.

Re: ThreadOptions ReuseThread not working

Posted: Wed Jan 02, 2019 8:10 am
by jvierra
Also note the following about ThreadOptions.
PS D:\scripts> $host.Runspace.ThreadOptions = 1
Exception setting "ThreadOptions": "The thread options can only be changed if the apartment state is multithreaded apartment (MTA), the current
options are UseNewThread or UseCurrentThread, and the new value is ReuseThread."
Also

$host.Runspace.ThreadOptions.value__ = [System.Management.Automation.Runspaces.PSThreadOptions]::UseNewThread

is the correct method for setting this.

As David notes - some host implantations may not have this. You likely need a WMF 3 or later Net Framework host and the apartment type selected (MTA/STA).

Re: ThreadOptions ReuseThread not working

Posted: Wed Jan 02, 2019 8:44 am
by jvierra
With the Sapien implementation this is the "$host" in use:
Name : PrimalScriptHostImplementation
Version : 3.0.0.0
InstanceId : 12d52fb0-3fc8-431c-8c72-7aba3be25b4f
UI : System.Management.Automation.Internal.Host.InternalHostUserInterface
CurrentCulture : en-US
CurrentUICulture : en-US
PrivateData :
DebuggerEnabled : True
IsRunspacePushed :
Runspace :