Click here to Skip to main content
15,896,063 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I understand that in general a List is not thread safe. In my case I have a list on which I am traversing a specific object which contains a list inside it. How can I make that list thread safe.

C#
lstToReturn = new list<item2>();

Parallel.ForEach(lstFromDb, variable=>
{
Item2 t = new Item2();
//Do some operation
lstOfItem2 = Get list from database related to variable
t.anotherList = lstOfItem2.Select(c => c.Id);

lock(lstToReturn)
{
    lstToReturn.add(t)
}
}


Here I am not getting "anotherList" right all time.
It is some time skipping values.

How can I solve this problem?
Please note data is large so I have to go for parallel behavior.<
Posted
Updated 15-Jun-15 21:54pm
v2

1 solution

Create a new class that inherits from IList<T>.
Have a private member of type List<T>.
Implement the methods in a thread safe manner.
 
Share this answer
 
Comments
teek13 16-Jun-15 5:30am    
How can we handle situation when we have this method changing for different entities.
Can't we have something like AutoResetEvent like thing with enhanced performance?
InbarBarkai 16-Jun-15 5:56am    
If you are referring to internal changes that happens in an object that is in the list, than it should be handled within the object.
If you are referring to changes that are made to the list itself than an AutoResetEvent if a good solution

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