michidk
michidk

Reputation: 350

C# Multithreading: Do I have to use locks when only getting objects from a list/dictionary?

I am currently working on a multithreaded c# application.

In my case, I have a list/dictionary, which is assigned and filled in the main-thread while the application is starting up. The list will never be modified again. I only use the list to get objects.

Do I have to use locks?

lock(list) { var test = list[0]; }

or can I access the object directly?

I know, if I access the object in the list, the object has to be thread-safe.

Upvotes: 1

Views: 321

Answers (4)

Kosala W
Kosala W

Reputation: 2143

As others have mentioned, reading is not a problem. But as you said, you are populating this collection at start up. But you have not mentioned at what point are you starting to read. So presumably there can be unexpected behaviours. You have to use thread safe collections for that. For an example you can use a blocking collection for this purpose.

Here is the MSDN article which explains more about thread safe collections Link.

Upvotes: 0

skywalkerytx
skywalkerytx

Reputation: 244

Lock is used to avoid fetching dirty reads if there's other thread . Since you won't change it, list is lock-free.

If you really want to prevent some unexpected changes for debugging (get error when it happens), you can declare it as const.

Upvotes: 0

Boas Enkler
Boas Enkler

Reputation: 12557

Reading is not a problem. But be sure that unexpected behaviors can appear if someone else is writing/deleting. When you are reading

if this list is prepared before and not changed after this you could access the object without locking which is also faster.

But be really aware that you should strongly avoid and modification action to happend when you read from the collection.

When you need also the writing operations then you would need synchronization like with ReaderWriterLockSlim or have a look at the system.collections.concurrent namespace

Upvotes: 5

René Vogt
René Vogt

Reputation: 43946

As long as you don't change the content of the list/array, there is no immediate need for locks.

But I would suggest to implement some synchronization (like locks) anyway. Can you be sure that you won't change your application in the next years so that you will change the content later at runtime?

Upvotes: 2

Related Questions