sharing global variable in Parallel.ForEach

jasneet

Member
Joined
Nov 20, 2014
Messages
5
Programming Experience
1-3
Is There any way to share global object variable value inside the Parallel.ForEach ,for example only one task can access it and update it's value at one time during this time other task will wait and so on.
It will be really helpful if i can get some code example.

i check the How to: Write a Parallel.For Loop with Thread-Local Variables but i am looking the way to share global value among the parallel task.
 
The first thing to consider is whether it actually makes sense to use Parallel.ForEach at all if you have to share writeable data. Maybe it does and maybe it doesn't. Even if synchronised access to the data keeps it safe, it may mean that parallelism is pointless because it provides no speed increase.

Assuming that it does make sense to use parallelism, the most obvious option is to use a lock statement to ensure that only one thread can access a resource at a time. There might be other appropriate options too, like a ReaderWriterLockSlim if the resource is read often and written to occasionally.
 
Thanks for the replying.
could you please clear my one doubt, if i am accessing some variable which is defined outside the Parallel.ForEach ,the value of this variable be will be shared among the all thread, if it's value changes by one thread .
for example if i am using
_String inside the Parallel.ForEach ,Does the value of _String will be shared to all thread,whenever it got change by any thread?



public string _StringResult runTest{ Parallel.ForEach ( ....
..... ); }
 
let me rephrase again.
if how do i use reference object (failedCheck) inside the parallel-foreach ,so all task can update the reference object one at a time .
could you please help me how to convert below function in parallel-foreach ?

private Result RunNonWatchers(ref HealthCheck failedCheck)
{
foreach (Check check in applicableChecks)
{
if (HealthCheck.value=="ERROR")
break;
failedCheck = checkError(ref failedCheck);
//some other independent function
}
}
 
let me rephrase again.
if how do i use reference object (failedCheck) inside the parallel-foreach ,so all task can update the reference object one at a time .
could you please help me how to convert below function in parallel-foreach ?

private Result RunNonWatchers(ref HealthCheck failedCheck)
{
foreach (Check check in applicableChecks)
{
if (HealthCheck.value=="ERROR")
break;
failedCheck = checkError(ref failedCheck);
//some other independent function
}
}

I already told you what to do in post #2. Instead of rephrasing, how about rereading?
 
Back
Top Bottom