When you new up a new list in C# in multiple threads, does each thread get its own instance of a list?
So my code looks similar to this:
List<Item> _items = new List<Item>();
public void Method(List<List<Batch>> batches) {
Parallel.ForEach(batches, parallelOptions, (batch, state) => CalculateAndAddToList(batch))
}
private void CalculateAndAddToList(List<Batch> batch) {
//Some computations
var localItems = new List<Item>();
foreach(var b in batch) {
//Computations of newItems
localItems.AddRange(newItems);
}
_items.AddRange(items);
}
I will randomnly get an error that says: "Destination array was not long enough. Check destIndex and length, and the array's lower bounds." at the line that says: "localItems.AddRange(newItems)". Since each thread is newing up its own list instance of localitems, I figured other threads wouldn't be changing it, so why am getting that error on that line?
I figured I'd need a lock around "_items.AddRange(items)" since multiple threads access and change the shared field "_items", but I have yet to get a threading error to throw on that line.