在C#并发集合 [英] Concurrent collections in C#

查看:155
本文介绍了在C#并发集合的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在寻找在C#或至少是一个集得到一个并发收集的方式,支持并行枚举。现在,我得到一个InvalidOperationException集合时在其上我迭代变化。我可以只复制深收集并配有私人拷贝工作,但我不知道是否有可能是一个更好的办法



代码段:

 的foreach(字符串S IN(列表<串GT;)callingForm.Invoke(callingForm.delegateGetKillStrings))
{
//做一些爵士
}

- 编辑 -



我把答案,但也发现,我需要确保这是写入所需的收集代码试图获得一个锁。

 私人无效addKillString(String s)将
{
锁(killStrings)
{
killStrings.Add(S);
}
}


解决方案

其他不是做深复制你最好的选择可能是锁定集合:

 列表<串GT;的thelist =(列表<串GT;)callingForm.Invoke(callingForm.delegateGetKillStrings); 
锁(theList.SyncRoot){
的foreach(字符串s中的thelist){
//做一些爵士
}
}


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

Code snippet:

foreach (String s in (List<String> )callingForm.Invoke(callingForm.delegateGetKillStrings))
    {
        //do some jazz
    }

--edit--

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆