简体   繁体   English

线程安全枚举,在C#中添加或删除集合

[英]Thread safe enumeration, add or removal of a collection in c#

I have faced a question in interview I am not sure I understood it correctly . 我在面试中遇到一个问题,我不确定我是否理解正确。 Would it really be real time scenario?? 真的是实时场景吗? But I am trying my best to explain the problem 但是我正在尽力解释这个问题

Create a class that is to be collection(implement IEnumerable) and it will have a data structure(a dictionary) which will have very large chunk of data. 创建一个要收集的类(实现IEnumerable),它将具有一个数据结构(一个字典),该数据结构将包含非常大的数据块。 User can iterate this data. 用户可以迭代此数据。 But this class should also provide an option of adding and removing item to data structure. 但是此类还应提供一个向数据结构添加和删除项目的选项。 It is accessible to so many threads. 许多线程都可以访问它。 So while a thread is iterating over the collection other thread might be adding an item this collection. 因此,当一个线程遍历该集合时,其他线程可能正在向该集合添加一个项目。 So, thread which is iterating should also retrieve the latest added item. 因此,正在迭代的线程也应该检索最新添加的项。

So how the class would look like 那班的样子

Starting by version 4.0 .net already provides such kind of collections. 从4.0版开始,.net已经提供了此类集合。

Take a look at the System.Collections.Concurrent-Namespace . 看一下System.Collections.Concurrent-Namespace And a deeper look into the ConcurrentBag and the ConcurrentDictionary classes. 更深入地了解ConcurrentBagConcurrentDictionary类。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM