列表的Threadsafe foreach枚举 [英] Threadsafe foreach enumeration of lists

查看:53
本文介绍了列表的Threadsafe foreach枚举的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要枚举对象的通用IList<>.列表的内容可能会更改,就像其他线程添加或删除的一样,这将终止我的枚举,并带有修改了集合;枚举操作可能不会执行."

I need to enumerate though generic IList<> of objects. The contents of the list may change, as in being added or removed by other threads, and this will kill my enumeration with a "Collection was modified; enumeration operation may not execute."

在IList上进行线程安全foreach的一种好方法是什么?大概不克隆整个列表.无法克隆列表引用的实际对象.

What is a good way of doing threadsafe foreach on a IList<>? prefferably without cloning the entire list. It is not possible to clone the actual objects referenced by the list.

推荐答案

对列表进行克隆是最简单,最好的方法,因为它可以确保您的列表不会在您的身下改变.如果该列表太大而无法克隆,请考虑在该列表周围放置一个锁,在对其进行读/写操作之前必须先将其锁上.

Cloning the list is the easiest and best way, because it ensures your list won't change out from under you. If the list is simply too large to clone, consider putting a lock around it that must be taken before reading/writing to it.

这篇关于列表的Threadsafe foreach枚举的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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