The Task Parallel Library (TPL) is a set of public types and APIs in the System.Threading and System.Threading.Tasks namespaces.
Question:How to maintain consistency in a variable that is shared among several threads in Task parallel library?
Description:I am using task parallel library to run a for loop on all of my CPU cores, but I am just thinking that the resultant of all the operation performed is not going to be what I want? Is there a way to perform operations on a class level variable shared with multiple threads so that the answer of Parallel.For() doesn't return inconsistent value! For learning purpose I have written a simple code chunk as follows which is always returning less than 10000000 int total = 0; Parallel.For(0, 10000000, (i) => { total++; }); Console.WriteLine(total); Console.ReadKey();
Posted by: Peter Andre | Posted on: Mar 15, 2019