I am having trouble using the Parallel.For method. I am making a GET call to get back a list. Then I want to take that list and add it to the main list. I have tried addRange which is not thread safe, and will return the wrong data in the list. I have also tried to use ConcurrentBag which also does not get the right data. When I say does not get the right data I mean some of the data in the lists is either repeating or gets over written.
Here is my code(updated):
var thisLock = new Object();
var list = new List<Person>();
Parallel.For(1, 10, x =>
{
request.Page = x;
response = Get(request); // call to client
lock(thisLock)
{
list.AddRange(response);
}
}
Any other ideas besides addRange or ConcurrentBag
lock, you should define a specific locking object instead. Regardless, aConcurrentBag<T>is the recommended collection for what you are trying to do. The fact that your data is "duplicated" suggests to me that your server is returning duplicate data rather than the code somehow duplicating it.