Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it thread safe to get an element by index from List

Tags:

c#

Is it thread safe to get an element by index from List?

var list = new List<int>();
...
var a = list[i]; //executed from multiple threads. Should this be protected?
like image 740
ren Avatar asked Oct 17 '25 05:10

ren


1 Answers

It is absolutely thread safe... ...as long as you can make sure that the list is not changed. Even adding items puts you into "not defined" territoty (although depending on implementation it may just work).

So, read only - yes. Read + manipulation: no.

Note: it is ok to change items IN the lsit as long as the list[5] for example is the same object. The list does not care. Not saying it will work - because depending what you would change here that would be your contract with the objects in the list. For ints you obviously should not update them.

like image 156
TomTom Avatar answered Oct 19 '25 20:10

TomTom



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!