gpt4 book ai didi

c# - 从 List 对象中添加和删除项目是否安全?

转载 作者:行者123 更新时间:2023-12-03 13:15:12 27 4
gpt4 key购买 nike

假设我们有多个线程和一个负责保存实时数据的公共(public) List。我们有一些线程负责将数据添加到列表对象。另一个线程负责从列表对象中获取数据,然后从顶部删除项目。

问题:在单独的线程中从 List 的开头删除并同时将数据添加到列表的末尾是否安全? List对象是如何实现的?

最佳答案

来自 docs :

Public static members of this type are thread safe. Any instance members are not guaranteed to be thread safe.

It is safe to perform multiple read operations on a List, but issues can occur if the collection is modified while it's being read.

因此,如果您的收藏可以被某些线程修改 - 您需要 lock它在写入读取操作时。

文档还为您指出了另一种解决方案:

For collections with built-in synchronization, see the classes in the System.Collections.Concurrent namespace.

ConcurrentQueue , 例如。使用 .Enqueue(obj) 将其插入队列末尾,使用 TryDequeue(out obj) 从队列顶部获取它。

关于c# - 从 List 对象中添加和删除项目是否安全?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60965734/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com