sooqua sooqua - 2 months ago 21
C# Question

How can I lock in just one place

I have two threads and a

Queue<string>
. The first thread doing some performance critical work in a loop and it checks the
Queue<string>
each iteration, grabbing the string if
Queue
is not empty.

Now I need the second thread to safely put strings in a
Queue
. Only the second thread should wait when the 1st thread isn't doing anything with the
Queue
. I don't want to use
lock
because it will be blocking the 1st thread eventually slowing it down.

How can I do that? I tried to surround only
Enqueue()
in my 2nd thread with the lock statement, but the ReSharper is warning me that:


the field is sometimes used inside synchronized block and sometimes used without synchronization.


So I guess I'm not doing it right.

Answer

Either don't use Queue or don't use lock (but a ReaderWriterLock for example). In this case I suggest ConcurrentQueue<T>.