4

I am new to multithreading and have a question on sharing objects. I am doing this in C# .Net 4.5

I have an list that contains a object called Price. The class Price contains 12 properties one of type datetime and the others are of type double.

I then run 4 tasks which all reference this object List. None of the tasks will change the List object they are just reading from the object.

So the fact the tasks are all referencing the same object but only reading from it am I right to think that I will not need any locking?

mHelpMe
  • 6,336
  • 24
  • 75
  • 150
  • You're right, no lock is required for reading. – Adriano Repetti Nov 20 '13 at 11:32
  • possible duplicate of [Passing parameter into a Task.Factory.StartNew](http://stackoverflow.com/questions/20047046/passing-parameter-into-a-task-factory-startnew) – Liam Nov 20 '13 at 11:32
  • As in the question above, *Your lambda will be hoisted out into a compiler generated class.* – Liam Nov 20 '13 at 11:34

2 Answers2

5

Yes the read does not modify anything for those types (and indeed most types), so it's safe.

David S.
  • 5,965
  • 2
  • 40
  • 77
3

Until and unless you do not have update and add going on any other thread you do not need to add locking. If update or edit is going on any other thread then do consider to use locking.
ReaderWriterLockSlim provides an easy and efficient way to provide advanced Reader and Writer locks.

Moreover as mentioned in Thread Safety section in documentation,

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.

Deepak Bhatia
  • 6,230
  • 2
  • 24
  • 58