sooqua sooqua - 1 year ago 105
C# Question

How can I lock in just one place

I have two threads and a

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

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

How can I do that? I tried to surround only
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 Source

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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download