I have a C# program, where I'm spawning a thread to do some calculations. I'm then adding the result of the calculations to a Queue, and from the main thread, I'm constantly checking to see if the Queue has length more than 0. If it does, then the result of the calculation is de-queued and used elsewhere.
I've read that I should lock the queue when accessing it from either thread because it may cause problems if both threads are accessing it at the same time. But should I lock it whenever I do ANYTHING with the Queue, or only when en-queuing/de-queuing?
E.g.
// In main thread
lock (meshDataQueue) {
if (meshDataQueue.Count > 0)
{
constructMesh(meshDataQueue.dequeue())
}
}
vs.
if (meshDataQueue.Count > 0) {
lock (meshDataQueue)
{
constructMesh(meshDataQueue.dequeue())
}
}