并发集合在C# [英] Concurrent collections in C#
问题描述
我正在寻找一种在C#中获取并发集合的方法,或者至少一个支持并发枚举器的集合。现在当我迭代的集合发生变化时,我得到一个InvalidOperationException。我可以只是深复制集合,并使用私人副本,但我想知道是否可能有更好的方法
I'm looking for a way of getting a concurrent collection in C# or at least a collection which supports a concurrent enumerator. Right now I'm getting an InvalidOperationException when the collection over which I'm iterating changes. I could just deep copy the collection and work with a private copy but I'm wondering if there is perhaps a better way
代码片段:
foreach (String s in (List<String> )callingForm.Invoke(callingForm.delegateGetKillStrings))
{
//do some jazz
}
- 编辑 -
我采用了答案,但也发现我需要确保写入集合的代码需要尝试获取锁。
I took the answer but also found that I needed to ensure that the code which was writing to the collection needed to attempt to get a lock as well.
private void addKillString(String s)
{
lock (killStrings)
{
killStrings.Add(s);
}
}
推荐答案
比起深度复制,你最好的打赌可能是锁定集合:
Other than doing a deep-copy your best bet might be to lock the collection:
List<string> theList = (List<String> )callingForm.Invoke(callingForm.delegateGetKillStrings);
lock(theList.SyncRoot) {
foreach(string s in theList) {
// Do some Jazz
}
}
这篇关于并发集合在C#的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!