集合遍历的线程安全问题
2017-08-09 08:52
239 查看
以下内容引用自MSDN:
Remarks
The wrapper returned by this method locks the queue before an operation is performed so that it is performed in a thread-safe manner.
To guarantee the thread safety of the
Queue, all operations must be done through this wrapper only.
Enumerating through a collection is intrinsically not a thread-safe procedure. Even when a collection is synchronized, other threads can still modify the collection, which causes the enumerator to throw an exception. To
guarantee thread safety during enumeration, you can either lock the collection during the entire enumeration or catch the exceptions resulting from changes made by other threads.
Examples
The following code example shows how to lock the collection using theSyncRoot during the entire enumeration.
This method is an O(1) operation.
Queue myCollection = new Queue();
lock(myCollection.SyncRoot)
{
foreach (object itemin myCollection)
{
// Insert your code here.
}
}
这是不是说,即使使用了Queue.Synchronized Method (Queue)方法来包装一个集合类,也无法确保集合的线程安全?
Remarks
The wrapper returned by this method locks the queue before an operation is performed so that it is performed in a thread-safe manner.
To guarantee the thread safety of the
Queue, all operations must be done through this wrapper only.
Enumerating through a collection is intrinsically not a thread-safe procedure. Even when a collection is synchronized, other threads can still modify the collection, which causes the enumerator to throw an exception. To
guarantee thread safety during enumeration, you can either lock the collection during the entire enumeration or catch the exceptions resulting from changes made by other threads.
Examples
The following code example shows how to lock the collection using theSyncRoot during the entire enumeration.
This method is an O(1) operation.
Queue myCollection = new Queue();
lock(myCollection.SyncRoot)
{
foreach (object itemin myCollection)
{
// Insert your code here.
}
}
这是不是说,即使使用了Queue.Synchronized Method (Queue)方法来包装一个集合类,也无法确保集合的线程安全?
相关文章推荐
- 遍历list的线程安全问题
- java集合中的线程安全问题
- Java集合的有序无序问题和线程安全与否问题
- 线程(集合的线程安全问题)
- 集合框架的线程安全问题
- 关于Java集合类中线程安全与不安全问题笔录
- 集合的线程安全问题
- java线程安全问题之静态变量、实例变量、局部变量
- springmvc中controller注入request的线程安全问题
- 关于sheet线程安全问题
- java线程安全问题之静态变量、实例变量、局部变量
- 使用增强for循环遍历集合的时候操作集合的问题?
- Iterator遍历集合时不可以删除集合中的元素问题
- 集合ArrayList遍历修改问题
- action的线程安全问题
- servlet 的线程安全问题解析
- hibernate中session的线程安全问题
- 同步异步-线程并发安全问题
- 从volatile说到i++的线程安全问题
- java线程安全问题之静态变量、实例变量、局部变量