Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

List thread safe?

Tags:

c#

Can the following be considered thread safe due to the atomic operation appearance of the code. My main concern is if the lists needs to be re-sized it becomes non-thread safe during the re-sizing.

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);
}
like image 226
kasperhj Avatar asked Dec 17 '25 13:12

kasperhj


1 Answers

No. List<T> is explicitly documented not 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. 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.

like image 195
Jon Skeet Avatar answered Dec 20 '25 02:12

Jon Skeet



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!