您的位置:首页 > 其它

集合遍历的线程安全问题

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)方法来包装一个集合类,也无法确保集合的线程安全?
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: