Classes and runspace affinity
Classes in PowerShell have affinity with the runspace
the instance of a class was created within. This means that any method call made in a different runspace
is queued to run in the original runspace
.
This affinity can be shown by inspecting the runspace
ID. In a script executed within a newly created PowerShell runspace
, each ID will be different:
1..5 | ForEach-Object {
[PowerShell]::Create().
AddScript('[Runspace]::DefaultRunspace.Id').
Invoke()
}
The command above will show the individual runspace
IDs like those shown below:
2
3
4
5
6
In the example below, a class is defined, then an instance is created. The instance of the class is passed as an argument to a newly created runspace
to execute the method. Each execution of the Run
method will show the value 1
if the class instance is created in the interactive runspace
:
class WithAffinity {
[void] Run() {
[Console]::WriteLine([Runspace...