HiveBrain v1.2.0
Get Started
← Back to all entries
patterncsharpMinor

Multithreaded item-processing queue

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
itemprocessingqueuemultithreaded

Problem

I have this Queue declared in my class:

static private Queue QUEUE = new Queue();


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))
   {
       if (QUEUE.Count > 0)
       {
           ThreadPool.QueueUserWorkItem(ThreadProc, QUEUE.Dequeue());
        }
    }
}

 static private void ThreadProc(Object stateInfo)
 {
     //Do the work...
 }

Solution

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...
 }

Code Snippets

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

 static private void ThreadProc(Object stateInfo)
 {
     //Do the work...
 }

Context

StackExchange Code Review Q#10373, answer score: 4

Revisions (0)

No revisions yet.