Quantcast
Channel: The Official Scripting Guys Forum! forum
Viewing all articles
Browse latest Browse all 15028

How can I have threadsafe instance variables within Inlinescript block when using Powershell workflows?

$
0
0

I'm using PowerShell 3 and playing with Workflows and I have run across something curious. I am using an inlinescript block hold some code to represent a task that I want to run many instances of. What I have found is that variables declared within this inlinescript block can be accessed across parallel instances.

My sample here has the parallel process sleep for a random number of milliseconds but you can see from the console output that multiple concurrent processes may sleep for the same number of milliseconds. Sure, this is possible, but it's so often that it's clear the data is not threadsafe.

workflow Invoke-ForEachParallel
{
    param([string[]]$InputVars)
    foreach -parallel($Val in $InputVars)
    {
        inlinescript {"Executing using value $using:Val"
            [int]$i = get-random -min 200 -max 3000"`t$using:Val - Sleeping for $i milliseconds."
            start-sleep -Milliseconds $i"`tFinished processing using value $using:Val"
        }
    }
}  

cls
Invoke-ForEachParallel (1..50)

So, the question is: how can I get ensure that each concurrent process is working with its own variable, $i, instances?


Kevin Buchan


Viewing all articles
Browse latest Browse all 15028

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>