0

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.

sooqua
  • 418
  • 6
  • 16
  • 1
    Throwing it out there in case this fits your need. Can't you use [`ConcurrentQueue`](https://msdn.microsoft.com/en-us/library/dd267265(v=vs.110).aspx)? – Simon Belanger Sep 29 '16 at 17:56
  • Sounds like ConcurrentQueue can be useful https://msdn.microsoft.com/en-us/library/dd267265(v=vs.110).aspx – YuvShap Sep 29 '16 at 17:57
  • See [Jon Skeet's answer](http://stackoverflow.com/a/39602754/1771817) to a similar question I asked recently. Entering the lock for every manipulation of the Queue is what guarantees thread safety/memory visibility. – adv12 Sep 29 '16 at 17:59

1 Answers1

4

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

Theraot
  • 31,890
  • 5
  • 57
  • 86