-
-
Save dlwyatt/64cb59e87a9d8e826bef to your computer and use it in GitHub Desktop.
Complete test code for Lock-Object
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
$arrayList = New-Object System.Collections.ArrayList | |
$arrayList.AddRange(('a','b','c','d','e')) | |
$sessionstate = [System.Management.Automation.Runspaces.InitialSessionState]::CreateDefault() | |
$sessionstate.ImportPSModule("PSThreading") | |
$sessionstate.Variables.Add( | |
(New-Object System.Management.Automation.Runspaces.SessionStateVariableEntry('arrayList', $arrayList, $null)) | |
) | |
$runspacepool = [runspacefactory]::CreateRunspacePool(1, 2, $sessionstate, $Host) | |
$runspacepool.Open() | |
$ps1 = [powershell]::Create() | |
$ps1.RunspacePool = $runspacepool | |
# Note that the calls to Lock-Object in each PowerShell object are commented out here, to demonstrate what happens | |
# if you try to access objects concurrently without synchronization. Uncomment them to have a successful test. | |
$null = $ps1.AddScript({ | |
#Lock-Object $arrayList.SyncRoot { | |
for ($i = 1; $i -le 5; $i++) | |
{ | |
Start-Sleep -Milliseconds 200 | |
$null = $arrayList.Add($i) | |
} | |
#} | |
}) | |
$handle1 = $ps1.BeginInvoke() | |
$ps2 = [powershell]::Create() | |
$ps2.RunspacePool = $runspacepool | |
$null = $ps2.AddScript({ | |
#Lock-Object $arrayList.SyncRoot { | |
foreach ($i in $arrayList) | |
{ | |
Start-Sleep -Milliseconds 200 | |
$i | |
} | |
#} | |
}) | |
$handle2 = $ps2.BeginInvoke() | |
if ([System.Threading.WaitHandle]::WaitAll($handle1.AsyncWaitHandle) -and | |
[System.Threading.WaitHandle]::WaitAll($handle2.AsyncWaitHandle)) | |
{ | |
$ps1.EndInvoke($handle1) | |
$ps2.EndInvoke($handle2) | |
} | |
if ($ps1.HadErrors) | |
{ | |
foreach ($errorRecord in $ps1.Streams.Error) | |
{ | |
Write-Error -ErrorRecord $errorRecord | |
} | |
} | |
if ($ps2.HadErrors) | |
{ | |
foreach ($errorRecord in $ps2.Streams.Error) | |
{ | |
Write-Error -ErrorRecord $errorRecord | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment