Skip to content

Passing variables by reference to thread jobs is not correctly documented #7378

Closed
@martinprikryl

Description

@martinprikryl

Documentation Issue

PowerShell Scopes documentation says this about using variables to "Thread jobs":

The Using scope modifier is supported in the following contexts:

  • ...
  • Thread jobs, started via Start-ThreadJob or ForEach-Object -Parallel (separate thread session)

Depending on the context, embedded variable values are either independent copies of the data in the caller's scope or references to it.
...
In thread sessions, they are passed by reference. This means it is possible to modify call scope variables in a different thread. To safely modify variables requires thread synchronization.

To me, coming from C#/C++ background, passing by reference means that you can assign these variables and have the assigned value be available in the calling code.

Yet the following fails to run:

$foo = 1

Start-ThreadJob {
    Write-Host $using:foo
    $using:foo = 2
} | Wait-Job | Out-Null

Write-Host $foo

It errors on $using:foo = 2 with:

The assignment expression is not valid. The input to an assignment operator must be an object that is able to accept assignments, such as a variable or a property.

I assume it's not a bug in PowerShell, but rather the documentation does not really correctly document how the variable can be modified. That the actual variable cannot be modified, but if one passes something like an object or a hash table, one can modify its fields/contents. I.e. it is conceptually more like passing a pointer to an object by value, rather then passing a variable by reference.

Context of the issue

https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_scopes#the-using-scope-modifier

Originally posted on Stack Overflow:
Modifying PowerShell $using scope variables in thread started with Start-ThreadJob

Metadata

Metadata

Assignees

No one assigned

    Labels

    area-aboutArea - About_ topicsarea-coreArea - Microsoft.PowerShell.Core modulearea-parallelismArea - Parallel processing (ForEach-Object, Jobs, etc)

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions