Reputation: 829
The below code has been written to create a pool of arrays made of lists. I want to use it later in parallel foreach. To create the pool I want to copy over a pre-populated template.
List<candle>[] sourceCandleList = new List<candle>[3];
// populate sourceCandleList here with data
ConcurrentBag<List<candle>[]> poolList = new ConcurrentBag<List<candle>[]>();
int maxThreads = 64;
for (int i = 0; i < maxThreads; i++)
{
poolList.Add(sourceCandleList);
}
Does this create 64 deep copies of sourceCandleList? If not, is the ConcurrentBag still thread-safe?
The reason why I'm not sure is because all the lists in the ConcurrentBag seem to go empty if I clear sourceCandleList
like sourceCandleList.Clear()
.
Upvotes: 0
Views: 77
Reputation: 456
The ConcurrentBag itself is still thread-safe, but this code is ultimately just adding 64 pointers to the bag that all reference the same array of List objects. It's the same array added 64 times, so any change made to one array will happen to all of them.
You'd need to manually make a deep copy of each array, each list within each array, and potentially each candle (if that's a class and not an immutable struct). It'd end up looking something like:
for (int i = 0; i < maxThreads; i++)
{
List<candle>[] candleList = new List<candle>[3];
for (int j = 0; j < 3; j++)
{
candleList[j] = new List<candle();
foreach (candle c in sourceCandleList[j])
candleList[j].Add(new candle(c.field1,c.field2)); // If it's an immutable struct, you should be able to just .Add(c)
}
poolList.Add(candleList);
}
You could probably do it jiggier with LINQ, but I'm not sure which version of .NET you're running.
Upvotes: 1
Reputation: 829
@zfrank
Sorry, I could not post this as a comment.
Would the below also do the trick of creating a deep copy? In my understanding ConvertAll creates a deep copy.
for (int i = 0; i < maxThreads; i++)
{
List < candle >[] CandleList = new List<candle>[sourceCount];
for (int w = 0; w <= sourceCount - 1; w++)
{
CandleList[w] = sourceCandleList[w].ConvertAll(c => c);
}
poolList.Add(CandleList);
}
Upvotes: 0