c# - ConcurrentDictionary 和 Clear() 函数。使值导出线程安全而不会丢失数据

标签 c# multithreading dictionary thread-safety concurrentdictionary

任何使 ConcurrentDictionary 在值被导出到列表 ex 的情况下线程安全的想法,并且在该字典被清除之后。这样任何其他线程都无法在导出和清除之间添加数据。

像这样: "

List<data> list;
list = (List<data>)_changedItems.Values; //get values before clearing
_changedItems.Clear();

" 添加由其他线程使用函数 _changedItems.AddOrUpdate 完成

现在,如果某些线程在清除行之前将数据对象添加到集合中,那么在从字典中获取数据和清除内容之间可能会丢失新数据。

或者是在锁内添加和清除的唯一方法。

lock(object)
{
    List<data> list;
    list = (List<data>)_changedItems.Values;  
    _changedItems.Clear();
}

lock(object)
    _changedItems.AddOrUpdate

需要一个清除函数来安全地返回字典中所有已清除的项目..

-拉里

最佳答案

的确,在一个序列中调用两个线程安全的方法并不能保证序列本身的原子性。您是对的,lock 获取值和清除的调用是必要的。

关于c# - ConcurrentDictionary 和 Clear() 函数。使值导出线程安全而不会丢失数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8987121/

相关文章:

multithreading - 多线程控制台输出?

Javascript 将字符串拆分为数组字典(键 -> 值)(正则表达式)

c# - 索引 switch 语句,或等效的? .net, C#

c# - 如何在 Visual Studio 中查看 Markdown 文本?

c# - Serilog - 日志文件的路径

java - 使用 SwingWorker java 在线程池中等待任务

c++ - 为什么 std::thread 缺少基本功能?

javascript - ES6 map : Why/When to use an object or a function as a key?

c# - 如何用\"修复JSON?

c# - 预测 Excel 如何使用 Postgres 函数解释字符串