Question

I have a trouble with getting perfect result using Parallel.

What I did

protected void Page_Load(object sender, EventArgs e)
{
    List<int> listInt = new List<int>();
    for (int i = 0; i < 10000; i++)
    {
        listInt.Add(i);

    }
    int cnt = 0;
    Parallel.ForEach(listInt, num =>
        {
            cnt++;
        }
    );
    System.Threading.Thread.Sleep(0);
    //it should show 10000 but it gives random result
    Response.Write(cnt);
}

I was expecting to get 10000 as response but it is giving random result.

What I am doing wrong to get the accurate result.

Live test is here.

Thank you so much.

Était-ce utile?

La solution

Your code is not threadsafe.

You can use something like this:

private static readonly object SyncRoot = new object();

and

lock (SyncRoot)
{
    cnt++;
}

Check this dotnetfiddle http://dotnetfiddle.net/D7QoP9

Autres conseils

Your code is not "threadsafe", that is a "Race".

Add a lock around cnt++ to see the expected result.

Or just use

Interlocked.Increment(ref cnt);
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top