I was reading this question and noticed the OP was iterating a list to queue up items into a ConcurrentQueue.
ConcurrentQueue<TaskClass> cq = new ConcurrentQueue<TaskClass>();
for (int x = 0; x < TaskList.Count; x++)
cq.Enqueue(TaskList[x]);
Is this necessary?
Is there a way to either:
You will note that ConcurrentQueue<T>
provides a constructor which accepts an IEnumerable<T>
and copies its contents, like so:
ConcurrentQueue<TaskClass> queue = new ConcurrentQueue<TaskClass>(TaskList);
Why would this be faster than enqueuing each item one-by-one? Because being a constructor it is not bound by the type's thread-safety guarantee and, therefore, can get away with adding items without taking out any locks (additionally, if you look at the source you will see that Microsoft deliberately bypass some volatile
field reads and writes for perf reasons).
See Reference Source for proof.
P.S. Unless you're creating large concurrent queues in a tight loop you are unlikely to observe a noticeable difference in performance, but it's worth remembering that the copy constructor is there if you need it.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With