Click here to Skip to main content
15,883,835 members
Please Sign up or sign in to vote.
4.00/5 (1 vote)
See more:
Hi All,

I'm tried Parallel Linq for adding data to an object. but some of the values are missing when clicking the button multiple times. The code is

C#
BindingList<object> addnew = new BindingList<object>();
System.Threading.Tasks.Parallel.For(0, 1000, i =>
                addnew.Add(
                new object()
                )
                );
MessageBox.Show(addnew.Count.ToString());


please give a solution if any one know about this.
Posted
Updated 27-Jul-12 0:08am
v4

1 solution

If you look at the MSDN page for BindingList[^] you will see the following at teh bottom:
"Any public static (Shared in Visual Basic) members of this type are thread safe. Any instance members are not guaranteed to be thread safe."

This means that the threads are interfering with each other! You need to use a lock of some form:
C#
BindingList<object> addnew = new BindingList<object>();
    System.Threading.Tasks.Parallel.For(0, 1000, i => AddOne(addnew));
    MessageBox.Show(addnew.Count.ToString());
    }
private void AddOne(BindingList<object> list)
    {
    lock (list)
        {
        list.Add(new object());
        }
    }
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900