List shared between threads: build a new list in a specific thread
referencing elements of the shared list?
Let's say I have this static list which is shared between different threads:
public static List<myClass> fooList = new List<myClass>();
Now, I want to access this shared list in a thread to build its own
private list, I would like to do the following:
List<myClass> newFooList = new List<myClass>();
lock (fooList)
{
foreach (myClass element in fooList)
{
newFooList.Add(element);
}
}
But if I do so, I'm building a new list which is referencing the same
elements as the shared list, so if later I access the newFooList without
any lock (as it should be) I'm actually accessing the same elements of the
shared list, hence violating the lock, right?
So, the solution is to make new elements in newFooList with the same
content as the ones in fooList instead of passing the references?
No comments:
Post a Comment