Reputation: 797
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:
Queue.Synchronized()
to get a wrapper, and if so: will that impact performance compared to the original queue?Upvotes: 3
Views: 1336
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