从不同线程迭代集合
我有一些线程,它们从一个列表中添加、删除、选择,显然,我收到异常:InvalidOperationException,原因集合因另一操作而更改。所以,我明白,我的代码设计不好等等。 问题来了: 这种情况下最简单的方法是什么,如何在不重写整个代码的情况下改善情况?
I have some threads, which adds,deletes,select from one List, and obviously, I'm getting Exception: InvalidOperationException, cause collection was changed due to another operation. So, i understand, that its bad design of my code, and etc.
Here goes the question:
what is the easyeist way from such situation, how can i improve situation without rewriting whole code?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
如果您只需要并发插入、更新和删除,您可以编写自己的
IList
实现,聚合常规列表并使用lock(...)
保护所有读写操作(如包含、添加等)。以安全方式枚举列表也是可能的,但需要您复制其内容,而不是仅仅将枚举器返回到内部列表。
您还可以考虑使用 .NET 4.0 中的新并发集合。虽然没有
ConcurrentList
,但您可以使用ConcurrentQueue
代替。If you only need to insert, update, and delete concurrently, you can write your own implementation of
IList<T>
that aggregates a regular list and useslock(...)
to protect all read and write operations (like Contains, Add, etc).Enumerating the list in safe manner is also possible, but would require that you make a copy of its contents rather than just returning an enumerator to the inner list.
You could also look at using the new concurrent collections in .NET 4.0. While there is no
ConcurrentList<T>
, you may be able to useConcurrentQueue<T>
instead.最简单的方法是使用
lock
构造,如下所示:这将一次只允许 1 个线程访问该列表。为了安全起见,您在使用该列表的任何地方都需要一个
锁
。The easiest way is to use the
lock
construct, like this:This will allow only 1 thread at a time to access the list. You'll need a
lock
anywhere that you're using the list to be safe.