4
\$\begingroup\$

I have this Queue declared in my class:

static private Queue<SignerDocument> QUEUE = new Queue<SignerDocument>(); 

I fill this Queue with some items to process, and I want to process it using multithreading.

Did I need to use lock in this case, to ensure that QUEUE.Dequeue is thread-safe?

static protected void ThreadProcManager()
{     
   lock (typeof(Queue<SignerDocument>))
   {
       if (QUEUE.Count > 0)
       {
           ThreadPool.QueueUserWorkItem(ThreadProc, QUEUE.Dequeue());
        }
    }
}

 static private void ThreadProc(Object stateInfo)
 {
     //Do the work...
 }
\$\endgroup\$
1
  • 1
    \$\begingroup\$ Is there a reason you are using a queue object to buffer work items for ThreadPool.QueueUserWorkItem (which is itself a queue)? The most intuitive behavior would be to perform the ThreadPool.QueueUserWorkItem call immediately where you would currently be doing a QUEUE.Enqueue call. If for some reason you do need this batching behavior, you really need to write a wrapper class for Queue which locks all access calls, such as Count, Peek, Enqueue, Dequeue, etc. \$\endgroup\$
    – Dan Lyons
    Commented Mar 28, 2012 at 17:33

2 Answers 2

4
\$\begingroup\$

Yes, and don't lock on typeof - highly unrecommended. Also you'll need to lock whatever's adding to the QUEUE so that the multithreaded Dequeue() does not race against it.

static protected void ThreadProcManager()
{     
   lock (QUEUE)
   {
       if (QUEUE.Count > 0)
       {
           ThreadPool.QueueUserWorkItem(ThreadProc, QUEUE.Dequeue());
        }
    }
}

 static private void ThreadProc(Object stateInfo)
 {
     //Do the work...
 }
\$\endgroup\$
0
0
\$\begingroup\$

Queue.Dequeue() is not threadsafe, so you need to lock it if it's called from multiple threads.

However, there's not enough information here to say for sure whether a lock is required in this particular case. The call to QUEUE.Dequeue() is not done from a ThreadPool worker, it's done in the ThreadProcManager() function. So the question is really whether you call ThreadProcManager(), or any of the other methods on QUEUE, from multiple threads.

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.