Skip to main content

The following example passes a thread-safe .NET ConcurrentDictionary object to all child jobs to collect uniquely named process objects. Since it is a thread safe object, it can be safely used while the jobs run concurrently in the process.

# Using ConcurrentDictionary to collect thread-safe items in PowerShell
#
# The following example passes a thread-safe .NET ConcurrentDictionary object
# to all child jobs to collect uniquely named process objects. Since it is a
# thread safe object, it can be safely used while the jobs run concurrently
# in the process.
#
# [Thread jobs and variables](https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_thread_jobs?view=powershell-7.4#thread-jobs-and-variables)

$threadSafeDictionary = [System.Collections.Concurrent.ConcurrentDictionary[string, object]]::new()
$jobs = Get-Process | ForEach-Object {
    Start-ThreadJob {
        $proc = $using:_
        $dict = $using:threadSafeDictionary
        $dict.TryAdd($proc.ProcessName, $proc) | Out-Null
    }
}
$jobs | Wait-Job | Receive-Job

$threadSafeDictionary.Count
# 96

$threadSafeDictionary['pwsh']
# NPM(K)  PM(M)   WS(M) CPU(s)    Id SI ProcessName
# ------  -----   ----- ------    -- -- -----------
#   112  108.25  124.43  69.75 16272  1 pwsh