There are many ways to thread synchronization, and if you are just sharing integer data, you can use interlocked for synchronization.
Here is an example of how to use interlocked for synchronization.
I. Illustrative examples
1 int 0 ; 2 Parallel.For (110001, i =3 {4 1; 5 }); 6 " Results: " + sum;
Looking at the code above, after 10,000 parallel loops, the last value of the sum variable is expected to be 10000. However, due to resource conflicts, the final value of sum is not deterministic, and most cases are less than 10000.
Second, the solution
There are a number of ways to synchronize, such as using a single object to synchronize. However, here we use interlocked to synchronize, the code is as follows:
1 int 0 ; 2 Parallel.For (110001, i =3 {4 Interlocked.Increment (ref sum); 5 }); 6 " Results: " + sum;
Run the sum value of 10000 for each run.
Implementing thread synchronization with interlocked