Search code examples
c#asp.netmultithreadingparallel.foreach

System.Threading.Tasks.Parallel


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.


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