Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should you lock resources when reading values?

When doing thread synchronization in C# should I also lock an object when I read a value or just changing it?

for example I have Queue<T> object. Should I just lock it when doing the Enqueue and Dequeue or should I also lock it when checking values like Count?

like image 692
RoboDev Avatar asked Jan 10 '09 15:01

RoboDev


1 Answers

From MSDN:

A Queue<(Of <(T>)>) can support multiple readers concurrently, as long as the collection is not modified. Even so, enumerating through a collection is intrinsically not a thread-safe procedure. To guarantee thread safety during enumeration, you can lock the collection during the entire enumeration. To allow the collection to be accessed by multiple threads for reading and writing, you must implement your own synchronization.

You should ensure no reader is active while an item is queued (a lock is probably a good idea).

Looking at the count in reflector reveals a read from a private field. This can be okay depending on what you do with the value. This means you shouldn't do stuff like this (without proper locking):

if(queue.Count > 0)
    queue.Dequeue();
like image 73
Cristian Libardo Avatar answered Oct 02 '22 16:10

Cristian Libardo