Value storage during Parallel Processing

2020-03-26 06:23发布

问题:

I just tried out this simple program... nothing fancy..

double[] a = new double[100000];
double[] b = new double[100000];

List<double> a1 = new List<double>();
List<double> b1 = new List<double>();

for (Int64 i = 0; i < 100000; i++)
{
    a[i] = i;
    a1.Add(i);
}

Parallel.For(0, 100000, delegate(Int64 i)
{
    b[i] = i;
    b1.Add(i);
});

According to this code, 100000 numbers must be stored in a, b, a1, b1 each. But at times, the variable b1 (List updated by the Parallel Process) has less than 100000 numbers (Keeps varying between 90000 and 100000). I wonder why...

回答1:

List<T> is not thread-safe for multiple threads to be writing simultaneously, as described on the MSDN page. You must synchronize access (defeating the purpose of multiple threads) or use a thread-safe collection. There are thread-safe collections available in the System.Collections.Concurrent namespace.