[英]creating a ConcurrentBag using a template
編寫下面的代碼來創建由列表組成的數組池。 我想稍后在foreach中並行使用它。 要創建池,我想復制一個預填充的模板。
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);
}
這會創建sourceCandleList的64個深層副本嗎? 如果不是,那么ConcurrentBag仍然是線程安全的嗎?
我不確定的原因是因為如果我像sourceCandleList.Clear()
一樣清除sourceCandleList
,則ConcurrentBag中的所有列表似乎都為空。
ConcurrentBag本身仍然是線程安全的,但是此代碼最終僅添加了指向所有引用相同List對象數組的bag的64個指針。 同一陣列被添加了64次,因此對一個陣列所做的任何更改都將發生在所有陣列上。
您需要手動復制每個數組,每個數組中的每個列表以及每個蠟燭的深層副本(如果這是一個類,而不是一個不變的結構)。 最終看起來像:
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);
}
您可能可以使用LINQ來使它更加靈活,但是我不確定您正在運行哪個.NET版本。
@zfrank抱歉,我不能發表此評論。
下面是否還會創建深層副本的技巧? 以我的理解,ConvertAll創建一個深層副本。
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);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.