Using thread-safe objects
Several classes in .NET offer thread safety. This means that an instance of an object can be made accessible from runspaces that are, to a limited degree, synonymous with threads that share a common parent.
Thread-safe objects can be used with anything that makes use of runspaces, including jobs created by Start-ThreadJob
, ForEach-Object -Parallel
, event handlers, and runspaces.
The Start-Job
command, as it is running in a separate process, cannot make use of the techniques explored here.
One of the simpler-to-use thread-safe objects is a hashtable. The hashtable is created using the Synchronized
static method of the Hashtable
type:
$synchronizedHashtable = [Hashtable]::Synchronized(@{
Key = 'Value'
})
The synchronized hashtable can be added to an InitialSessionState
object and then used within a script or command that is running in a runspace. The changes made to the hashtable within the runspace are visible outside: