gpt4 book ai didi

c# - 列出线程安全?

转载 作者:行者123 更新时间:2023-11-30 13:57:17 25 4
gpt4 key购买 nike

由于代码的原子操作外观,是否可以将以下内容视为线程安全的。我主要担心的是,如果列表需要调整大小,它在调整大小时会变成非线程安全的。

List<int> list = new List<int>(10);

public List<int> GetList()
{
var temp = list;
list = new List<int>(10);
return temp;
}

TimerElapsed(int number)
{
list.Add(number);
}

最佳答案

没有。 List<T>明确是 documented 不是是线程安全的:

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. To ensure thread safety, lock the collection during a read or write operation. To enable a collection to be accessed by multiple threads for reading and writing, you must implement your own synchronization. For collections with built-in synchronization, see the classes in the System.Collections.Concurrent namespace. For an inherently thread–safe alternative, see the ImmutableList class.

关于c# - 列出线程安全?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22011609/

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