Skip to content

Instantly share code, notes, and snippets.

@dlwyatt
Created April 12, 2014 18:09
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dlwyatt/64cb59e87a9d8e826bef to your computer and use it in GitHub Desktop.
Save dlwyatt/64cb59e87a9d8e826bef to your computer and use it in GitHub Desktop.
Complete test code for Lock-Object
$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