avance70
avance70

Reputation: 797

System.Collections.Queue<T>, threads, locking and synchronization

I have a Queue<T> field that is accessed by various threads. Enequeue() is called from multiple threads many times per second, while there is a single thread that performs the Dequeue() and Count operations.

I havent been thinking much about this until now, since I played it "safe" and used lock on a static object before any operations with this queue. While there currently aren't any performance issue, I would like to get rid of the locks if they are redundant. My questions are:

  1. since I never iterate through the queue, are locks really needed in this situation? I mean, will the program crash when it happens that one thread enqueues and the second thread dequeues elements at exactly the same time?
  2. should I perhaps use Queue.Synchronized() to get a wrapper, and if so: will that impact performance compared to the original queue?

Upvotes: 3

Views: 1336

Answers (1)

Marc Gravell
Marc Gravell

Reputation: 1062855

1: yes they are necessary; both enqueue and dequeue mutate state; a standard queue is not thread safe

2: ConcurrentQueue<T> would work nicely; personally I use a version I wrote here on SO, Creating a blocking Queue<T> in .NET? - it makes it easy to throttle the size of the queue, and do efficient dequeues without looping

Note; with your current implementation the lock-object should only be static if the queue is static (that isn't clear in the question, though) - otherwise all your similar queues may be sharing a lock

Upvotes: 3

Related Questions